Functions in Python
User Defined Functions
1
Function
• A function is a block of organized, reusable code that is used
to perform a single, related action.
• Functions provide better modularity for your application and a
high degree of code reusing.
2
Function
Defining a Function
•The code block within every function starts with a colon (:) and
is indented.
•The statement return [expression] exits a function, optionally
passing back an expression to the caller.
• A return statement with no arguments is the same as return
None.
3
Function
Defining a Function
•Function blocks begin with the keyword def followed by the
function name and parentheses ( ( )).
•Any input parameters or arguments should be placed within
these parentheses. You can also define parameters inside these
parentheses.
•The first statement of a function can be an optional statement -
the documentation string of the function or docstring.
4
User Defined Functions
• User defined function
without parameters
• User defined function with
Parameters
5
Python Function With Arbitrary Arguments
• Sometimes, we do not know
in advance the number of
arguments that will be
passed into a function. To
handle this kind of situation,
we can use arbitrary
arguments in Python.
• Arbitrary arguments allow us
to pass a varying number of
values during a function call.
• We use an asterisk (*)
before the parameter name
to denote this kind of
argument.
6
User Defined Functions
• For variable length arguments
• For unspecified no of arguments, star is used with the
variable name
7
User Defined Functions
• Without printing arg1 • Without return statement
• Works fine
8
User Defined Functions
• Works perfectly, if Variable Parameters are NIL
• But needs compulsory Parameter, else raises error
9
User Defined Functions
• Function that calculates sum
of Variable length
parameters
10
User Defined Functions
• Using Return statement in
the function
• Value 6 gets printed on
executing the function
• Storing the Value returned in
some variable x
• Printing the value of that
Variable
11
User Defined Functions
12
User Defined Functions
• Function to find max of 2 nos with
return statement
• Return value stored in variable
• Error on Passing Strings as a
parameter
13
User Defined Functions
• Function to fins max of 3 nos with
return statement
14
User Defined Functions
• Minimum of 3 nos using List • Average of 3 nos using List
15
Recursion: function calling itself
def factorial(n):
if n==0:
return 1
else:
return n*factorial(n-1)
num = int(input("Enter a number: "))
print("The factorial of a {0} is: ".format(num), factorial(num))
Output:
16
Lambda Function
17
Lambda Function
• A lambda function is a small anonymous function.
• A lambda function can take any number of arguments, but
can only have one expression.
Syntax
lambda arguments : expression
• The expression is executed and the result is returned:
Example
• Add 10 to argument a, and return the result:
x = lambda a : a + 10
print(x(5))
18
Lambda Function
Lambda functions can take any number of arguments:
Example
• Multiply argument a with argument b and return the result:
• x = lambda a, b : a * b
print(x(5, 6))
Example
• Summarize argument a, b, and c and return the result:
• x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
19
Why Use Lambda Functions?
• The power of lambda is better shown when you use them as
an anonymous function inside another function.
• Say you have a function definition that takes one argument,
and that argument will be multiplied with an unknown
number:
• def myfunc(n):
return lambda a : a * n
20
• Use that function definition to make a function that always
doubles the number you send in:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
print(mydoubler(11))
21
• Or, use the same function definition to make a function that
always triples the number you send in:
Example
def myfunc(n):
return lambda a : a * n
mytripler = myfunc(3)
print(mytripler(11))
22
Example
HRA=24% of Basic or a
Ta=2700 Rs
23
• Or, use the same function definition to make both functions,
in the same program:
Example
def myfunc(n):
return lambda a : a * n
mydoubler = myfunc(2)
mytripler = myfunc(3)
print(mydoubler(11))
print(mytripler(11))
• Use lambda functions when an anonymous function is
required for a short period of time.
24
• Or, use the same function
definition to make both
functions, in the same
program:
Example
• HRA=24% of Basic or a
Ta=2700 Rs
• HRA=56% of Basic or a
Ta=2700 Rs
25
Python filter() Function
• Python filter() function is used to get filtered elements.
This function takes two arguments, first is a function
and the second is iterable. The filter function returns a
sequence from those elements of iterable for which
function returns True.
• The first argument can be None if the function is not
available and returns only elements that are True.
Syntax:
filter (function, iterable)
Parameters:
• function: It is a function. If set to None returns only
elements that are True.
• Iterable: Any iterable sequence like list, tuple, and
string.
26
Example filter()
27
Use filter() with lambda
28
Map() function
• The python map() function is used to
return a list of results after applying a
given function to each item of an
iterable(list, tuple etc.)
Syntax:
map(function, iterables)
Parameters:
• function- It is a function in which a map
passes each item of the iterable.
• iterables- It is a sequence, collection or
an iterator object which is to be mapped
29
Example
30
Use lambda function with map() function
31
Range() function
• Python range() function returns an immutable
sequence of numbers starting from 0, increments
by 1 and ends at a specified number.
Syntax:
range(start, stop, step)
Parameters:
• start (optional) : It is an integer number that
specifies the starting position. The Default value
is 0.
• stop (optional) : It is an integer that specifies the
ending position.
• step (optional) : It is an integer that specifies the
increment of a number. The Default value is 1.
32
Example
33