Functions in Python
Functions in Python
It contains statements, which are sequentially executed from top to bottom by python
Interpreter.
Once defined, a function can be called repeatedly from different places of the program
without writing same code of that function every time, or it can be called from inside
another function, by simply writing the name of the function and passing the required
parameters, if any.
Increases readability, particularly for longer code as by using functions, the program is
better organized and easy to understand.
Reduces code length as same code is not required to be written at multiple places in a
program. This also makes debugging easier.
Increases reusability, as function can be called from another function or another program.
Thus, we can reuse or build upon already defined functions and avoid repetitions of
writing the same piece of code.
Work can be easily divided among team members and completed in parallel.
Types of functions
3. User defined functions: These are the functions defined by the programmer as per the
requirement.
Creating User defined function:
General format of User defined function:
Elements of a function:
i) Function header: The first line of a function definition that begins with the keyword def
and ends with a colon(:). It specifies the name of the function and its parameters, if any.
ii) Parameters: Parameters are the variable(s)/value(s) provided in the parenthesis when
we write function header. These are the values required by function to work.
eg. def Area(radius):
A=3.14*radius*radius
If there is more than one value required by the function to work on, then, all of them
will be listed in parameter list separated by comma.
iii) Function body: The block of indented statements beneath function header that defines
the action performed by the function. The function may or may not return a value.
iv) Function call: A function call is an expression containing the function name followed by
parenthesis, (). If the function has been defined to receive parameters, the values that are
to be sent into the function are listed inside the parentheses of the function call operator.
List of arguments should be supplied in same way as parameters are listed. Bounding of
parameters to arguments is done 1:1, and so there should be same number of arguments
as mentioned in parameter list.
Example of argument in function call
>>> area (5)
5 is an argument.
An argument can be literal, variable, or expression.
Flow of Execution:
Flow of Execution refers to the order in which statements are executed during program run.
When the interpreter encounters a function definition, the statements inside the function are
not executed until the function is called. Later, when the interpreter encounters a function
call, the control jumps to the called function and executes the statement of that function.
After that, the control comes back the point of function call so that the remaining statements
in the program can be executed..
Example:
1. Trace the flow of execution for the following programs:
1 def calsum(x , y ) :
2 z=x+y
3 return z
4
5 num1 = int(input (“Enter first number”))
6 num2 = int(input(“Enter second number”))
7 sum = calsum(num1, num2 )
8 print(“Sum of 2 numbers=”, sum
Type 1: User defined function without arguments and without return value(void functions
without any arguments).
Eg.
def add( ):
A = int(input (“Enter first number”))
B = int(input(“Enter second number”))
C=A+B
print(“Sum of 2 numbers=”, C)
add( )
Type 2: User defined functions without arguments and with return value (fruitful
functions without any arguments)
Eg)
def add( ):
A = int(input (“Enter first number”))
B = int(input(“Enter second number”))
C=A+B
return C
Result = add()
print(“Sum of 2 numbers=”, Result)
Type 3: User defined functions with arguments and without return value (void functions
with some arguments)
Eg)
def add(a,b ) :
C=a+b
print(“Sum of 2 numbers=”, C)
X = int(input (“Enter first number”))
Y = int(input(“Enter second number”))
add(X, Y )
Type 4: User defined functions with arguments and with return value (fruitful
functions with some arguments)
E.g.
def add(a, b ) :
C=a+b
return C
X = int(input (“Enter first number”))
Y = int(input(“Enter second number”))
Result = add(X, Y)
print(“Sum of 2 numbers=”, Result)
Caller: The function calling another function is called the Caller. In the above example _main_
is the caller of add( ).
Called function / Callee: The function being called is the Called function. In the above
example add( ) is the called function.
The values received in the function definition/function header are called parameters. They
are also known as formal arguments or formal parameters.
Eg;)
def add(a,b ) :
C=a+b
print(“Sum of 2 numbers=”, C)
X = int(input (“Enter first number”))
Y = int(input(“Enter second number”))
add(X, Y )
2) Default arguments:
A parameter having default value in the function header is known as a default
parameter.
The default values are specified in the function header of function definition.
A default argument can be skipped in function call statement.
The default values for parameters are considered only if no value is provided for that
parameter in the function call statement.
ii) void functions or non-fruitful functions: These are functions not returning any values.
The functions that return some computed result in terms of a value is called non void
functions.
The computed value is returned using return statement. The value being returned can be
one of the following:
i) a literal
ii) a variable
iii) an expression
Eg)
return 5 # literal being returned
return 6+4 # an expression involving literals being returned
return a # variable being returned
return a**3 #expression involving variable and literal, being returned
return (a+8**2)/ b # expression involving variables and literal, being returned
return a+b/c # expression involving variables being returned
NOTE 1: The returned value of a function should be used in the caller function inside an
expression or a statement.
Eg)
def sum (x,y) :
S=x+y
return S
add_result = sum(3,5) # The returned value being used in assignment statement
print(sum(3,4)) # The returned value being used in print statement
sum(4,5) > 6 # The returned value being used in a relational expression
NOTE 2 : The return statement ends a function execution even if it is in the middle of the
function.
Eg)
import math
def check(a):
a = math.fabs(a)
return a
print (a) #This statement is unreachable because check( ) function will end
#with return and control will never reach this statement
check(-15)
NOTE 3: Returning multiple values.
In Python , a function may return multiple values. In multiple returning , it returns a
sequence of values to the calling statement.
To return multiple values from a function ,
i) The return statement inside a function body should be of the form:
return <value1/variable1/expression1> , <value1/variable1/expression1> , ………
ii)The function call statement should receive or use the returned values in one of the
following ways:
return
Eg)
#void function but no return statement #void function with a return statement
def greet( ): def quote ( ):
print(“helloz”) print(“Goodness counts!!”)
return
The void functions are generally not used inside a statement or expression in the caller;
their function call statement is standalone complete statement itself.
Eg)
greet( )
greet1(NAM)
quote( )
prinsum(4,6,9)
Local Scope: A name declared in a function-body is said to have local scope i.e. it can be used
only within this function and the other blocks container under it.
Lifetime of a variable:
The time for which a variable remains in memory is called Lifetime of a variable.
Differentiate between Local variable and Global variable.
A local variable has local scope A global variable has global scope
E.g. E.g.
def calsum(x , y ) : def calsum(x , y ) :
z=x+y z=x+y
return z return z
num1 = int(input (“Enter first number”)) num1 = int(input (“Enter first number”))
num2 = int(input(“Enter second number”)) num2 = int(input(“Enter second number”))
sum = calsum(num1, num2 ) sum = calsum(num1, num2 )
print(“Sum of 2 numbers=”, sum) print(“Sum of 2 numbers=”, sum)
NOTE: When a local variable is created with same name as that of global variable, it hides
the global variable in function definition.
To use a global variable inside local scope when the same variable name is having local scope
as well as global scope, the keyword global should be prefixed before the variable.
Syntax:
global < variable name>
E.g.
def state1( ) :
global tigers #This is an indication that not to create local variable with the name tigers
tigers = 15 #rather use global variable tigers
print(tigers)
tigers = 95
print(tigers)
state1( )
print(tigers)
o/p:
95
15
15
NOTE:
1) Once a variable is declared global in a function, you cannot undo the statement (ie, after
a global statement, the function will always refer to the global variable and local variable
cannot be created by the same name).
2) Although global variables can be accessed through local scope, but it is not a good
programming practice, So keep global variables global and local variables local.
Passing immutable arguments and mutable arguments in function call:
1) Passing immutable arguments in function call.
When immutable type arguments (eg. Numbers, strings etc.) are passed in a function call
then any change in its value will also change the memory address it is referring to. So after
returning from the function definition the originally passed variable remains unchanged.
E.g.
def change(x):
x+=5
print("Change made in function: ",x)
a=10
print("Value of a before function call: ",a)
change(a)
print("Value of a after function call: ",a)
Output:
Value of a before function call: 10
Change made in function: 15
Value of a after function call: 10
Example 1:
def myFunc1(myList):
print(" \t Inside myFunc1( )")
print(“\t List received:” , myList)
myList[0] += 2
print(“ \t List within called function, after changes: “, myList)
return
List1 = [1]
print("List before function call: ", List)
myFunc1(List1) #passing argument is a list, a mutable type
print("List after function call: ”, List1)
Output:
List before function call: [1]
Inside myFunc1( )
List received: [1]
List within called function, after changes: [3]
List after function call: [3]
Example 2: Passing Mutable Type Value to a function – Adding /Deleting items to it
def myFunc2(myList):
print(" \t Inside myFunc2( )")
print(“\t List received:” , myList)
myList.append(2)
myList.extend( [5,1] )
print(“ \t List after adding some elements : “, myList)
myList.remove(5)
print(“\t List within called function, after all changes:”, myList)
return
List1 = [1]
print("List before function call: ", List1)
myFunc2 (List1) #passing argument is a list, a mutable type
print("List after function call : ”, List1)
Output:
List before function call: [1]
Inside myFunc2( )
List received: [1]
List after adding some elements: [1,2,5,1]
List within called function, after all changes:”.[1,2,1]
Example 3: Passing Mutable Type Value to a function – Assigning parameter to a new
value or variable
def myFunc3(myList):
print(" \t Inside myFunc3( )")
print(“\t List received:” , myList)
new = [3,5]
myList = new
myList . append(6)
print(“\t List within called function, after all changes:”, myList)
return
List1 = [1, 4]
print("List before function call: ", List1)
myFunc3 (List1) #passing argument is a list, a mutable type
print("List after function call: ”, List1)
Output:
List before function call: [1,4]
Inside myFunc3( )
List received: [1,4]
List within called function, after all changes: [3,5,6]
List after function call : [1,4]
********************