0% found this document useful (0 votes)
3K views16 pages

Functions in Python for Class 12 CS

1. A function is a block of code that performs a specific task and can be called anywhere in a program. It contains a definition with a name, parameters, and a body. 2. Functions allow for code reuse and modular programming. Parameters pass input values to a function and the function can return values. 3. Variables used inside a function are local, while global variables defined outside a function can be accessed inside but not modified unless declared global. The LEGB rule determines variable scope.

Uploaded by

Jagan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3K views16 pages

Functions in Python for Class 12 CS

1. A function is a block of code that performs a specific task and can be called anywhere in a program. It contains a definition with a name, parameters, and a body. 2. Functions allow for code reuse and modular programming. Parameters pass input values to a function and the function can return values. 3. Variables used inside a function are local, while global variables defined outside a function can be accessed inside but not modified unless declared global. The LEGB rule determines variable scope.

Uploaded by

Jagan
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Functions

What is a function?

Function is a group of related statements that perform a specific task


Syntax: function definition

def function_name(parameters):

"""docstring"""

statement(s)

return <value> #optional

A function definition consists of following components.

1. Keyword def marks the start of function header.


2. A function name to uniquely identify it. Function naming follows the same rules of
writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function. They are
optional.
4. A colon (:) to mark the end of function header.
5. Optional documentation string (docstring) to describe what the function does.
6. One or more valid python statements that make up the function body. Statements
must have same indentation level (usually 4 spaces).
7. An optional return statement to return a value from the function.

Function Examples:

def greet(name):
"""This function greets to
the person passed in as
parameter"""
print("Hello, " + name + ". Good morning!")
def add(a,b):

return a+b

def calc(a,b):

add=a+b

sub=a-b

mul= a*b

return add,sub,mul

result= calc(10,20)

print( "the result obtained are")

for i in result:

print(i)

Function Call or invoking a function:


A function call is just the function’s name followed by parentheses, possibly with some number of
arguments in between the parentheses.

When the program execution reaches these calls, it will jump to the top line in the function and
begin executing the code there. When it reaches the end of the function, the execution returns to
the line that called the function and continues moving through the code as before.

Syntax:- Function_name(actual parameters)

Write functions for add,sub,mul,div,average,minimum,maximum, of 2 numbers,

area of rectangle,triangle, square.

Return Values:

return statement is used to return a value from the function.


We can return multiple values through single return statement as explained in above
example program in function calc(a,b)

Parameters and Arguments in Functions:

Parameters are values provided in the parantheses,(), in the function header. Also called formal
parameters or formal arguments.

Arguments are values that are passed to a function when it is called. Also called actual parameters or
actual arguments.
Functions can be called using following types of formal arguments −
• Positional arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
[Link] arguments
These are arguments passed to a function in correct positional order.
def subtract(a,b):
print(a-b)
subtract(100,200)
subtract(200,100)

2. Keyword arguments - the caller identifies the arguments by the parameter name
def fun( name, age,gender ):
print ("Name: ", name)
print ("Age ", age)
print ("Gender ", gender)
fun( age=15, gender="F" ,name="abcd")
We can use positional and keyword arguments together. first we have to provide positional
argument then key word argument. if positional after keyword then error.
fun('xyz', gender='M',age=16) is correct
fun(name='xyz', gender='M',16) returns error

[Link] arguments
that assumes a default value if a value is not provided to arguments
def sum(x=3,y=4):
z=x+y
return z
r=sum()
print(r)
r=sum(x=4)
print(r)
r=sum(y=45)
print(r)
r=sum(9)
print(r)
NOTE: while defining default argument, non default argument cannot follow default
argument. Example:
def Fun(x=5,y) : -------------- is wrong
def Fun(y,x=5) : -------------- is correct

[Link]-length arguments
We can pass variable number of arguments to a function using *(asterisk) symbol in python.
def sum(*a): IN ALL THESE CASES,a is stored as tuple. Eg for 3 rd sum(). a=(20,30)
total=0
for x in a:
total = total + x
print(" The sum is:", total)
sum()
sum(20)
sum(20,30)
sum(20,30,40,50)

variable length keyword arguments


def add(**d): d={‘x’:10,’y’:20}
sum=0
print(d)
for i in d:
sum=sum+d[i]
print("sum",sum)

add()
add(x=10)
add(x=10,y=20)
add(x=10,y=20,z=30)
add(x=10,y=20,z=30,a=40)

IMPORTANT POINTS FOR CALLING A FUNCTION


 While calling a function , we cannot use positional argument after keyword
argument. Example:
for a function fun defined by fun(name,gender,age)
fun('xyz', gender='M',age=16) is correct
fun(name='xyz', gender='M',16) returns error
 While defining a function, we cannot define a normal formal argument after default
argument . Example:
def Fun(x=5,y) : -------------- is wrong
def Fun(y,x=5) : -------------- is correct
 While calling a function defined by variable length argument + normal argument
example: fun(name,*friends_names,age), whatever we input in calling the function
after name will go to *friends so only way to give a value for age is to use keyword
argument. Example:
fun(‘jagan’,’dog’,’dog2’) ------ ABSOLUTELY WRONG
the values for name,*friends_names,age are name=‘jagan’ ,
friends_name=(’dog’,’dog2’) , age= nothing so it returns error since only 2
mentioned.
Therefore one has to do like
fun(‘jagan’,’dog’,age=’dog2’)------ CORRECT ABSOLUTELY.

Scope of variable:
when a variable is created (assigned a value ) ,an object is created and assigned a value and
a reference is stored in the variable

What is scope?
Scope is the region of the program where a variable is accessible.
There are three types of variables based on the type of scope.
[Link] variable
[Link] variable
[Link] local variable
[Link] variable
It is accessible only inside the functional block where it is declared.
program:
def fun():
s = "I love India!" #local variable
print(s)
s = "I love World!"
fun()
print(s)

Output:
I love India!
I love World!

[Link] Variable
Any variable created outside of all the functions is global variable.
The global keyword:
With global, you're telling Python to use the globally defined variable instead of locally
defining it. To use it, simply type global, followed by the variable name.
Syntax:- global variable_name
We only need to use the global keyword in a function if we want to do assignments /
change them. global is not needed for printing and accessing.
def fun():
global s#accessing/making global variable for fun()
print(s)
s = "I love India!“ #changing global variable’s value
print(s)
s = "I love world!"
fun()
print(s)
Output:
I love world!
I love India!
I love India!
.Find theoutput of belowprogram
def fun(x, y): # argument/parameterx and y
global a
a = 10
x,y= y,x
b = 20
b = 30
c = 30
print(a,b,x,y)
a, b, x, y = 1, 2, 3,4
fun(50, 100) #passingvalue50 and 100 in parameterx and y of functionfun()
print(a, b, x, y)
Findtheoutput of below code
def fun():
print(x)
x=10
fun()
Find the output of below code
def fun():
global x
x=200
print(x)
x=10
fun()
print(x)
[Link] variable
It is accessible in nesting of functions, using nonlocal keyword.
The nonlocal keyword
The nonlocal statement is useful in nested functions. It causes the variable to refer to the
previously bound variable in the closest enclosing scope. In other words, it will prevent the
variable from trying to bind locally first, and force it to go a level 'higher up'.

Program:
def fun1():
x=100
def fun2():
nonlocal x #change it to global or remove this declaration
x = 200
print(x)
print("Before calling fun2: " ,x)
print("Calling fun2 now:")
fun2()
print("After calling fun2: " ,x)
x=50
fun1()
print("x in main: " ,x)
OUTPUT:
Before calling fun2: 100
Calling fun2 now:
After calling fun2: 200
x in main: 50
Differences between local and global variable.

Local Variable Global Variable


It is a variable which is
It is a variable which is declared within a declared outside of all
function or block functions
Accessible throughout the
Accessible within a function or block program in which it is declared
Python Scope Resolution
Python will check a name in below order
1. Local
2. Enclosed
3. Global
4. Built-in

LEGB rule

Find output of below: Global Variables Local Variables Local Variables


for fun
def Change(P ,Q=30): R S FOR FUN
callChange(R,S)
150 100 CHANGE(S)
P=P+Q
250 130 P Q P Q
Q=P-Q 150 100 100 30
250 150 130 100
print( P,"#",Q)
return (P)
R=150
S=100
R= Change(R,S)
Output:
print(R,"#",S)
S= Change(S) 250 # 150
250 # 100
130 # 100
Mutable and Immutable Objects w.r.t functions
A mutable object can change its state or contents and immutable objects cannot.

Everything in Python is an object,and every objects in Python can be either mutable or immutable.

Mutable objects:

list, dict, set

Immutable objects:

int, float, complex, string, tuple, bool

x=10
x=x+1

ie whenever you say x=10 , you create a new entry. When u say x=11 you create another new entry.
Where x =11. If this x=11 is inside function, it acts as if u mentioned a new variable x local. And refers
to it but this mutable ,doesn changes to original value itself therefore undergoing change when even
inside def.

NOTE: but if u mention like L=[2] inside def block L REEFERS to a new id hence

INSIDE L =/= OUTSIDE L

Parameter passing mechanism in python is determined by the mutability or immutability of


the object being passed to function.
Parameter Passing Mechanisms
Pass/Call by value: actual parameter values are copied to formal parameters. The values of
actual parameters cannot be changed by functions to which they are passed. If we pass
immutable objects to a function it behaves like pass by value.
Pass/Call by reference: The reference to actual parameter values are copied to formal
parameters. The values of actual parameters can be changed by functions to which they are
passed. . Generally If we pass mutable objects to a function it behaves like pass by
reference.

Passing String to a function


st= "abcdef"
def test(x):
x = "abcdef123456"
print("Inside Function:", x)
test(st)
print("Outside Function:", st)
Passing Tuple to a function
tup = (10,20)
def test(x):
x +=(30,)
print("Inside Function:", x)
test(tup)
print("Outside Function:", tup)

Passing List to a function


#Pass by reference
n = [10,20]
def test(x):
[Link](40)
print("Inside Function:", x)

test(n)
print("Outside Function:",n)

Output:

Passing Dictionary to a function


n = {'a':10,'b':20}
def test(x):
y={'c':30}
[Link](y)
print("Inside Function:", x)
test(n)
print("Outside Function:",n)

Functions using libraries


Mathematical functions:

Mathematical functions are available under math [Link] use mathematical functions under this
module, we have to import the module using import math.

For e.g.

To use sqrt() function we have to write statements like given below.

import math

r=[Link](4)

print(r)

OUTPUT : 2.0

MATH MODULE math [Link]


[Link]

Constants in Math Module:

p Mathematical constant, the ratio of circumference of a circle to it's diameter


i (3.14159...)

e mathematical constant e (2.71828...)


Functions available in Python Math Module

[Link] Function Description


Returns the smallest integer greater than or equal
1 ceil(x) to x.
2 floor(x) Returns the largest integer less than or equal to x
3 trunc(x) Returns the truncated integer value of x
4 copysign(x, y) Returns x with the sign of y
5 fabs(x) Returns the absolute value of x
6 factorial(x) Returns the factorial of x
7 fmod(x, y) Returns the remainder when x is divided by y
8 sqrt(x) Returns the square root of x
9 exp(x) Returns e**x
10 pow(x, y) Returns x raised to the power y
LOGARTHMIC FUNCTIONS
Returns the logarithm of x to the base (defaults to
11 log(x[, base]) e)
12 log1p(x) Returns the natural logarithm of 1+x
13 log2(x) Returns the base-2 logarithm of x
14 log10(x) Returns the base-10 logarithm of x
TRIGNOMETRIC RELATED FUNCTIONS
15 hypot(x, y) Returns the Euclidean norm, sqrt(x*x + y*y)
16 radians(x) Converts angle x from degrees to radians
17 degrees(x) Converts angle x from radians to degrees
18 sin(x) Returns the sine of x
19 cos(x) Returns the cosine of x
20 tan(x) Returns the tangent of x
21 asin(x) Returns the arc sine of x
22 acos(x) Returns the arc cosine of x
23 atan(x) Returns the arc tangent of x
24 sinh(x) Returns the hyperbolic cosine of x
25 cosh(x) Returns the hyperbolic cosine of x
26 tanh(x) Returns the hyperbolic tangent of x
27 asinh(x) Returns the inverse hyperbolic sine of x
28 acosh(x) Returns the inverse hyperbolic cosine of x
29 atanh(x) Returns the inverse hyperbolic tangent of x

String functions:

String functions are available in python standard [Link] are always

availble to use.

For e.g. capitalize() function Converts the first character of string to upper case.

s="i love programming"

r=[Link]()

print(r)

OUTPUT:

I love programming

string [Link]
Python Lambda
A lambda function is a small anonymous function which can take any number of arguments,
but can only have one expression.
E.g.
mult = lambda x,y,z : x* y*z
print(mult(5, 6,2))
OUTPUT:
60

Common questions

Powered by AI

Default arguments are values that are assigned to parameters when no corresponding argument is provided during the function call. For example, `def sum(x=3, y=4):` sets default values for `x` and `y` . Keyword arguments allow the caller to specify arguments by parameter name rather than position, providing greater clarity. For example, `fun(age=15, gender="F", name="abcd")` uses keyword arguments to explicitly define each parameter .

Local variables are declared within a function and are only accessible inside that function. For example, in the function `def fun(): s = "I love India!"`, `s` is a local variable and its value is accessible only within `fun()` . Global variables, on the other hand, are declared outside of all functions and can be accessed throughout the program. You can modify a global variable inside a function by using the `global` keyword. For instance, `def fun(): global s; s = "I love India!";` allows changes to `s` to persist outside the function .

Incorrectly mixing positional and keyword arguments can lead to errors. Positional arguments must come first; otherwise, Python raises a syntax error. For example, the function call `fun(name='xyz', gender='M', 16)` is incorrect, while `fun('xyz', gender='M', age=16)` is correct . This rule ensures clarity and prevents ambiguity in function calls.

Lambda functions in Python are anonymous functions defined without a name, using a concise syntax: `lambda arguments: expression`. They are useful for short, simple operations executed in-line, often when a small function is needed for a short period of time. For example, using `mult = lambda x, y, z: x* y*z` to quickly multiply three numbers on the fly . Lambda functions are preferred when function definitions are simple, and code readability isn't compromised.

The `global` keyword in Python is used inside a function to declare that a variable is global, enabling modification of a global variable's value within the function. Without `global`, any assignment to a variable's value within a function would create a local variable. For example, in the function `def fun(): global s; s = "I love India!";` using `global s` updates the global variable `s` instead of creating a new local one .

Passing tuples to functions behaves like 'pass by value' since tuples are immutable; modifying a tuple within a function does not affect the original tuple outside the function. For example, appending to a tuple inside a function creates a new tuple . However, passing lists to functions behaves like 'pass by reference'; lists are mutable, and changes made within the function, such as appending an element, will reflect on the original list due to shared reference .

Python's math module provides numerous mathematical functions beyond basic arithmetic, such as square roots (`math.sqrt`), logarithms (`math.log`), and trigonometric functions (`math.sin`, `math.cos`). Importing the module using `import math` is crucial as it simplifies complex expressions, makes code more readable, and prevents potential implementation errors in mathematical calculations by leveraging well-tested library functions .

The `nonlocal` keyword allows a variable defined in a nested function to refer to a variable from the nearest enclosing scope that is not global. For example, in the program `def fun1(): x=100; def fun2(): nonlocal x; x = 200;`, the `nonlocal x` in `fun2()` changes the value of `x` in `fun1()`, making `x` equal 200 after fun2's execution .

Variable-length arguments allow functions to accept an arbitrary number of arguments, making them flexible. Using `*` captures extra positional arguments as a tuple, e.g., `def sum(*args): return sum(args)`, where calling `sum(1, 2, 3)` would return 6. Similarly, using `**` captures extra keyword arguments as a dictionary, e.g., `def add(**kwargs): return sum(kwargs.values())`, enabling `add(x=10, y=20)` to return 30 .

In Python, parameter passing mechanism is determined by the mutability of the object being passed. 'Pass by value' occurs when immutable objects (like strings and tuples) are passed, copying values to formal parameters and not allowing changes within the function to affect outside the function. For instance, if a string is passed to a function and modified, the original string remains unchanged . 'Pass by reference' occurs when mutable objects (like lists and dictionaries) are passed, allowing functions to modify the original object. For example, passing a list to a function and modifying it inside the function affects the original list due to shared reference .

You might also like