Functions - Ipynb - Colaboratory
Functions - Ipynb - Colaboratory
Functions - Ipynb - Colaboratory
ipynb - Colaboratory
Function
A function is a block of code which only runs when it is called. You can pass data, known as
parameters, into a function. A function can return data as a result. The main advantage of functions
is Code Reusability
Defining a function
The return statement is used to exit a function and go back to the place from where it was called.
This statement can contain expression which gets evaluated and the value is returned.
If there is no expression in the statement or the return statement itself is not present inside a
function, then the function will return the None object.
def add_num(x,y):
sum = x+y
return sum
Calling a function
Parameters are inputs to the function. If a function contains parameters, then at the time of
calling,compulsory we should provide values, otherwise we will get error.
1. Positional/Required Parameters: the number of arguments must be same and the order of
arguments is important.
2. Keyword (i.e.,Parameter name) Parameters: order of the arguments is not important but the
number of arguments must be same.
3. Default Parameters: You can define default parameters for the arguments. If you are not
passing any argument, then values by default will be considered. After default arguments you
should not take normal arguments.
4. Variable length Parameters: Sometimes we can pass variable number of arguments to our
function. We can declare a variable length argument with '*' symbol as follows:
def f1(*n):
We can call this function by passing any number of arguments including zero number.
Internally all these values represented in the form of tuple.
return a+b
https://colab.research.google.com/drive/1qWdh_C8V6qfuF0tXS4wSp2uv_uWEyft9#printMode=true 2/7
18/11/2023, 19:18 Functions.ipynb - Colaboratory
def sum(a,b):
print(a+b) # This sum() function we can't use for the new requirement.
sum(10,20,30)
Now, Suppose if we want to pass any number of keyword arguments to a function. We can declare
key word variable length arguments also. For this we have to use **. We can call this function by
passing any number of keyword arguments. Internally these keyword arguments will be stored
inside a dictionary.
https://colab.research.google.com/drive/1qWdh_C8V6qfuF0tXS4wSp2uv_uWEyft9#printMode=true 3/7
18/11/2023, 19:18 Functions.ipynb - Colaboratory
def display(**kwargs):
for k,v in kwargs.items():
print(k,"=",v)
display(n1=10,n2=20,n3=30)
display(rno=100,name="abc",marks=70,subject="Python")
Some of the variable not even exist for the entire duration of a program.
So for this purpose we must understand the two things regarding this:
Scope of the variable : part of the program in which a variable is accessible is called its scope.
Lifetime of the variable : Duration for which the variable exists is called its lifetime.
Global Variable:
Global variables are those variables which are defined in the main body of the program or outside of
the function. These variables can be accessed in all functions of that module.
Local Variable:
A variable which is defined within a function is called as local to that function only. A local variable
can be accessed from the point of its definition until the end of the function in which it is defined.
a = 10 # Global Variable
def f1():
a = 20 # Local variable to the function 'f1'
print(a) # 20
def f2():
print(a) # 10
f1()
f2()
def f1():
xy = 10 # local variable of 'f1()'
print(xy)
def f3():
print(xy) # local variable of 'f1()' can not accessed by function 'f3()'
f1()
f3()
global keyword: We can use global keyword for the following 2 purposes:
https://colab.research.google.com/drive/1qWdh_C8V6qfuF0tXS4wSp2uv_uWEyft9#printMode=true 4/7
18/11/2023, 19:18 Functions.ipynb - Colaboratory
a=10
def f1():
global a
# To bring global variable to the function for required modification
a=7
# we are changing the value of the local variable
print(a)
def f2():
print(a)
f1()
f2()
Lambda Function: Sometimes we can declare a function without any name,such type of nameless
functions are called anonymous functions or lambda functions. The main purpose of anonymous
function is just for instant use(i.e., for one time usage). The lambda function can return only one
value and doesn't have any explicit return statement. It cannot access a global variable. We can use
lambda functions very commonly with filter(),map() and reduce() functions,because these functions
expect function as argument. We can define by using lambda keyword:
s=lambda a,b:a+b
print("The Sum of 10,20 is:",s(10,20))
print("The Sum of 100,200 is:",s(100,200))
filter() function: We can use filter() function to filter values from the given sequence based on some
condition. For example, we have 20 numbers and if we want to retrieve only even numbers from
them.
Syntax:
filter(function,sequence)
Where, function argument is responsible to perform conditional check. sequence can be list or tuple
or string.
https://colab.research.google.com/drive/1qWdh_C8V6qfuF0tXS4wSp2uv_uWEyft9#printMode=true 5/7
18/11/2023, 19:18 Functions.ipynb - Colaboratory
#without lambda
def isEven(x):
if x%2==0:
return True
else:
return False
l=[0,5,10,15,20,25,30]
l1=list(filter(isEven,l))
print(l1)
#with lambda
l=[0,5,10,15,20,25,30]
l1=list(filter(lambda x:x%2==0,l))
print(l1)
l2=list(filter(lambda x:x%2!=0,l))
print(l2)
map() function:
For every element present in the given sequence,apply some functionality and generate new
element with the required modification. For this requirement we should go for map() function.
Syntax:
map(function,sequence)
The function can be applied on each element of sequence and generates new sequence
#without lambda
l=[1,2,3,4,5]
def doubleIt(x):
return 2*x
l1=list(map(doubleIt,l))
print(l1)
[2, 4, 6, 8, 10]
#With Lambda
l=[1,2,3,4,5]
l1=list(map(lambda x:x*x,l))
print(l1)
https://colab.research.google.com/drive/1qWdh_C8V6qfuF0tXS4wSp2uv_uWEyft9#printMode=true 6/7
18/11/2023, 19:18 Functions.ipynb - Colaboratory
reduce() function:
reduce() function reduces sequence of elements into a single element by applying the specified
function.
Syntax:
reduce(function,sequence)
Note: reduce() function present in functools module and hence we should write import statement.
150
https://colab.research.google.com/drive/1qWdh_C8V6qfuF0tXS4wSp2uv_uWEyft9#printMode=true 7/7