Function in Python
Function in Python
x = 20
my_func()
print("Value outside function:",x)
Output: hello
Keyword Arguments
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
# 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-
>>>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)