Function in Python
def function_name( parameters ):
‘’’function_docstring’’’
function_suite
return [expression]
def my_func():
x = 10
print("Value inside function:",x)
x = 20
my_func()
print("Value outside function:",x)
Value inside function: 10
Value outside function: 20
Pass by Reference vs Value
def changeme( mylist1 ):
"This changes a passed list into this function"
print ("before change: ", mylist1)
mylist1[2]=50
print ("after change: ", mylist1)
return
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
• Here, we are maintaining reference of the passed object and appending values in
the same object.
• Therefore, this would produce the following result-
• before change: [10, 20, 30]
• after change: [10, 20, 50]
• Values outside the function: [10, 20, 50]
def changeme( mylist1 ):
"This changes a passed list into this function"
mylist1 = [1,2,3,4] # This would assign new reference in mylist
print ("Values inside the function: ", mylist1)
return
# Now you can call changeme function
mylist = [10,20,30]
changeme( mylist )
print ("Values outside the function: ", mylist)
• The parameter mylist is local to the function changeme.
• Changing mylist within the function does not affect mylist.
• The function accomplishes nothing and finally this would produce the following
result-
Values inside the function: [1, 2, 3, 4]
Values outside the function: [10, 20, 30]
Function Arguments
• You can call a function by using the following types of formal
arguments-
• Required arguments
• Keyword arguments
• Default arguments
• Variable-length arguments
Required Arguments
• the arguments passed to a function in correct positional order.
• the number of arguments in the function call should match exactly with the
function definition.
# Function definition is here
def printme( str ):
"This prints a passed string into this function"
print (str)
return
# Now you can call printme function
printme(‘hello’)
Output: hello
Keyword Arguments
• related to the function calls.
• the caller identifies the arguments by the parameter name.
• This allows you to
• skip arguments or
• place them out of order
• because the Python interpreter is able to use the keywords provided
to match the values with parameters.
def printme( strn ):
"This prints a passed string into this function"
print (strn)
return
# Now you can call printme function
printme( strn = "My string")
# Function definition is here
def printinfo( name, age ):
"This prints a passed info into this function"
print ("Name: ", name)
print ("Age ", age)
return
# Now you can call printinfo function
printinfo( age=50, name="miki" )
Default Arguments
• A default argument is an argument that assumes a default value if a value is not provided in the function call for
that argument.
def printinfo( name, age = 35 ):
print ("Name: ", name)
print ("Age ", age)
# Now you can call printinfo function
printinfo( age=50, name="miki" )
printinfo( name="miki" )
Name: miki
Age 50
Name: miki
Age 35
Variable-length Arguments
• You may need to process a function for more arguments than you specified while
defining the function.
• These arguments are called variable-length arguments and are not named in the
function definition, unlike required and default arguments.
def function_name([formal_args,] *var_args_tuple ):
function_stmt
return [expression]
• An asterisk (*) is placed before the variable name that holds the
values of all non keyword variable arguments.
• This tuple remains empty if no additional arguments are specified
during the function call.
# Function definition is here printinfo( 10 )
def printinfo( arg1, *vartuple ): printinfo( 70, 60, 50 )
print ("Output is: ")
print (arg1) Output is:
for var in vartuple: 10
print (var)
Output is:
70
60
50
The Anonymous Functions
• These functions are called anonymous because they are not declared in the
standard manner by using the def keyword.
• You can use the lambda keyword to create small anonymous functions.
• lambda operator can have any number of arguments, but it can have only one
expression.
• It cannot contain any statements and
• it returns a function object which can be assigned to any variable.
• An anonymous function cannot be a direct call to print because lambda requires
an expression.
• Lambda functions have their own local namespace and cannot access variables
other than those in their parameter list and those in the global namespace.
• Mostly lambda functions are passed as parameters to a function which expects a
function objects as parameter like map, reduce, filter functions
def add(x, y):
return x + y
# Call the function
add(2, 3)
# Output: 5
add = lambda x, y : x + y
print add(2, 3)
# Output: 5
• In lambda x, y: x + y; x and y are arguments to the function and x +
y is the expression which gets executed and its values is returned as
output.
• lambda x, y: x + y returns a function object which can be assigned to
any variable, in this case function object is assigned to
the add variable.
>>>type (add) # Output: function
• The syntax of lambda function contains only a single statement, which is as
follows-
lambda [arg1 [,arg2,.....argn]]:expression
# Function definition is here
>>>sum = lambda arg1, arg2: arg1 + arg2
# Now you can call sum as a function
>>>print ("Value of total : ", sum( 10, 20 ))
>>>print ("Value of total : ", sum( 20, 20 ))
Use of Lambda Function
• We use lambda functions when we require a nameless function for a short period
of time.
• In Python, we generally use it as an argument to a higher-order function (a
function that takes in other functions as arguments).
• Lambda functions are used along with built-in functions like filter(), map() etc.
filter()
filter(function, iterable)
• creates a new list from the elements for which the function returns True.
# Program to filter out only the even items from a list
my_list = [1, 5, 4, 6, 8, 11, 3, 12]
new_list = list(filter(lambda x: (x%2 == 0) , my_list))
print(new_list)
Output: [4, 6, 8, 12]
map()
map(function, iterable)
• It applies a function to every item in the iterable.
• We can use map() to on a lambda function with a list:
>>>M = [1,2,3,4,5]
>>>squaredList = list(map(lambda x: x*x, M))
>>>print(squaredList)
Reduce function
reduce(function, iterable)
• applies two arguments cumulatively to the items of iterable, from left to right.
>>>from functools import reduce
>>>list = [1,2,3,4,5]
>>>s = reduce(lambda x, y: x+y, list)
>>>print(s)
• In this case the expression is always true, thus it simply sums up the elements of
the list.
>>>def fahrenheit(T):
return ((float(9)/5)*T + 32)
>>>temp = [36.5, 37, 37.5,39]
>>>F = map(fahrenheit, temp)
>>>print(list(F))
[97.7, 98.600, 99.5, 102.2]
>>>temp = [36.5, 37, 37.5,39]
>>>F=map(lambda T:((float(9)/5)*T +32 ), temp)
>>>list(F)
[97.7, 98.600, 99.5, 102.2]
Global Vs Local variable
>>>total = 0 # This is global variable.
>>>def sum( arg1, arg2 ):
total = arg1 + arg2; # Here total is local variable.
print ("Inside the function local total : ", total) return total
# Now you can call sum function
>>>sum( 10, 20 )
>>>print ("Outside the function global total : ", total )
• Inside the function local total : 30
• Outside the function global total : 0