18 Working with Functions Part 2
18 Working with Functions Part 2
By Chirag Parikh
Cont. Returning values from Functions
By Chirag Parikh
Void functions
The functions that perform some action or do some work but do not return
any computed value or final value to the caller are called void functions.
By Chirag Parikh
Returning Multiple Values
Unlike other programming languages, Python lets you return more than one
value from a function.
Example:
def squared (x, y, z):
return x * x, y * y, z * z
t = squared (2, 3, 4)
print(t)
OR
v1, v2, v3 = squared(2, 3, 4)
print (v1, v2, v3)
By Chirag Parikh
Scope of Variable
The scope rules of a language are the rules that decide, in which part(s) of
the program, a particular piece of code or data item would be known and can
be accessed therein.
There are broadly two kinds of scopes in Python:
1. Global Scope
A name declared in top level segment (__main__) of a program is said to
have a global scope and is usable inside the whole program and all
blocks (functions, other blocks) contained within the program.
2. Local Scope
A name declared in a function-body is said to have local scope and can
be used only within this function and the other blocks contained
under it.
By Chirag Parikh
Use global variable in local scope
Output:
95
15
15
By Chirag Parikh
Mutable / Immutable Function
Arguments
Changes in immutable types are not reflected in the caller function at all.
Changes in mutable types
are reflected in caller function if its name is not assigned a
different variable or datatype.
are not reflected in the caller function if it is assigned a different
variable or datatype.
By Chirag Parikh
Passing immutable type value to a function
Output:
By Chirag Parikh
Passing a mutable type value to a function
By Chirag Parikh
Passing Function as Function Argument
By Chirag Parikh
Example of passing function as other
function argument
def add(x, y):
return x + y
def multiply(x, y):
return x * y
def apply_operation(func, x, y):
return func(x, y)
result = apply_operation(add, 3, 4)
print(result)
result = apply_operation(multiply, 3, 4)
Output:
7
print(result) 12
By Chirag Parikh
Python Lambda/Anonymous Functions
By Chirag Parikh
Example of Anonymous Function
Code:
a = lambda x, y : (x * y)
print(a(4, 5))
Output:
20
By Chirag Parikh
Recursion in Python
Any function that calls itself in its body repeatedly until a particular condition
becomes false and the target task is done is called a "Recursive function" and
this procedure is called "Recursion".
The most popular example of recursion is calculation of factorial.
Mathematically factorial is defined as −
n! = n × (n-1)!
5! = 5 × 4!
5 × 4 × 3!
5 × 4 × 3 × 2!
5 × 4 × 3 × 2 × 1!
5×4×3×2×1
= 120
By Chirag Parikh
Recursion Example
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n-1)
print ('factorial of 5 =', factorial(5))
Output:
factorial of 5 = 120
By Chirag Parikh