CH 3 - WORKING WITH FUNCTIONS
CH 3 - WORKING WITH FUNCTIONS
Functions help to break our program into smaller and modular chunks.
(OR)
It supports reusability.
Functions
The code/logic for these functions are already available in python library.
For example, sqrt() will work only when we import math module from library.
Like this math module, the python have ‘n’ number of modules in it.
import math
Example:
>>>import math
>>>print(math.sqrt(25))
(iii) User Defined Functions
It is unlike Built-in functions, These functions are defined by the
Programmers according to their requirements to perform specific task.
I.e. The user/programmer can write their set of codes(Own) inside of these
functions, whenever they need they can call their function again and again in
program.
PROPERTIES OF USER DEFINED FUNCTION
In Python, Every user defined function has two properties they are:
User defined
Function
Function Definition:
Function Call:
It helps to call the function definition by using its name with/without arguments.
Creating User Defined function
In Python, ‘def’ keyword is used to create user defined functions. To create
user defined functions we should do the following steps:
Step 1:
Every user defined function starts with def keyword followed by function
name with parentheses. This is known as function header.
Step 2:
Step 3:
After the header of the function, we should start body of the function
(I.e. Logic of the function) and it must be indented.
Syntax to create user defined function
The following syntaxes are used to create user defined function. We can create
user defined functions with parameter(s) or without Parameter.
Syntax 1: Example 1:
No Parameters
keyword Function name
Function’s header
def function_name( ): def Disp( ) : Ends with colon :
Example 2:
Syntax 2: Parameters_name
keyword Function name
Function
Body
PRACTICE QUESTIONS [1 (or) 2 Marks]
From the following questions identify keyword, function name and parameters
name.
Q.no 1: Answer:
Syntax 2: Example 2:
function_name( p1,p2,p3) def Square(a):
print(a**2)
Calling/Invoking
Square() with
Where, parameter(s).
Square(2)
p1,p2,p3 are values to be passed as
argument to the function definition.
Different ways of calling a user defined function
We can call the following function definition Add() using the following ways:
def Add(x,y):
print(x+y)
(i) Passing literal as argument to function call.
Ex:
Add(2,3)
(ii) Passing Variable as argument to function call.
Ex:
a, b=5,4
Add(a,b)
(iii) Taking input and passing input as argument to function call.
Ex:
a=int(input("Enter the first Number"))
b=int(input("Enter the Second Number"))
Add(a,b)
def Add(x,y):
return(x+y)
Ex:
Cube= 3 * (Add(5,6))
ACTUAL PARAMETER vs FORMAL PARAMETERS
Actual Parameters:
Actual parameters are available in function call statement, to send the value(s) from
calling function to called function.
Formal Parameters:
Note:
• If a function does not return any value then it is called, “void function” or “non-fruitful
function”.
• If a function return any value(s) then it is called, “non - void function” or “fruitful
function”.
EXAMPLES OF VOID AND NON-VOID FUNCTIONS
(i) Function with no parameter and (ii) Function with parameter(s) and
no return value: no return value:
def Add( ): def Add(a,b):
a,b=10,20 print(a+b)
print(a+b)
Add() #Calling Add() with no Arguments Add(10,20) #Calling Add() with two Arguments
(iii) Function with parameter(s) and (iv) Function with no parameter(s) and
with return value: with return value:
def Add(a,b): def Add( ):
z=a+b a,b=10,20
# Returning z value to calling
return z # Returning z value to calling func. return(a+b) function and it will store in R.
and it will store in R.
R= Add(10,20) #Calling Add() with two Arguments R=Add() #Calling Add() with no Arguments
print(“The Result is:“, R) print("The Result is:", R)
RETURNING VALUE/VALUES FROM THE FUNCTION
A function definition can return single value or multiple values from it.
calling function.
If return statement is not used inside the function, the function will return
‘None’ object.
RETURNING SINGLE VALUE FROM THE FUNCTION
We can return single value from the function in one of the following ways:
(i) A literal
(ii) A variable
(iii) An expression
EXAMPLE FOR RETURNING SINGLE VALUE
The ‘return’ keyword is used to return a multiple values from the function.
We can return multiple values from the function in one of the following ways:
Returning single value from the function(s) Returning Multiple values from the function
PRACTICE QUESTIONS [1 (or) 2 Marks]
From the following questions identify function header, function call, arguments,
parameters, function body.
Q.no 1: Answer:
def Cube( ): Function Header -> Cube():
a=2 Function call -> Cube()
print(a**3) Arguments -> No Argument(s)
Parameters -> No Parameter(s)
Cube() Function Body a=2
-> print(a**3)
Q.no 2: Answer:
def Disp(x,y): Function Header -> Disp(x,y):
print(x+y) Function call -> Disp(2,3)
Arguments -> 2, 3
Disp(2,3) Parameters -> x,y
Function Body -> print(x+y)
PRACTICE QUESTIONS [1 (or) 2 Marks]
From the following questions identify function header, function call, arguments,
parameters, function body and main program.
Q.no 3: Answer:
def Sum(a): Function Header -> Sum(a):
a=100 Function call -> Sum(b)
return a+3 Argument(s) -> b
Parameter(s) -> a
b=150
a=100
val=Sum(b) Function Body -> return a+3
PRACTICE QUESTIONS [2 Marks]
Find out the error(s) in the following program:
Q.no 1: Correct Code: Error 2 : Function header
should ends with colon.
Def Subjects( ) def Subjects( ):
a=100 Error1 a=100 Error 3
print(b) print(a)
Error 4: We must use Parentheses,
Subjects[ ] Subjects( ) to call the function.
print(p,q,r) print(p,q,r)
Error 2 – Missing one argument
during function call. Number of
arguments in function call should match
F(1,2) F(1,2,3 ) with number parameter in function
definition.(if default parameter is there
means then no problem).
PRACTICE QUESTIONS [2 Marks]
Find out the error(s) in the following program:
Q.no 5: Correct Code: Error 1 – Function header must
ends with colon.
def Total( ); def Total( ):
a=500 a=500 Error 2: It is a keyword. It
Return a return a should be in small letters.
print(Total()) print(Total())
print(p,q,r) print(p,q,r)
Error 1: Function should call with ( ).
print(Find[3,4]) print(Find(3,4))
FLOW OF EXECUTION IN FUNCTION CALL
Those statements which are not part of any function are called
“top level statements”. These top level statements are part of the main program.
Comment lines are ignored, all other non-blanks lines are executed.
If Python Notices, that it is a function definition, then Python just executes the
function header line to determine that it is proper function header and skip/ignores all
other function body.
The statements inside a function body are not executed until the function is called.
In Python, a function can define another inside it. But since the inner function is inside
the function body, the inner definition is not executed until the outer function is called.
When a code line contains function call, It jumps first to the function header and then
to the first line of the function body and starts executing it.
GUIDE LINES TO EXECUTE FUNCTION
A function ends with return statement or the last statement of function body,
whichever occurs earlier.
If the called function returns a value, then control will jump back to the function call
statement and completes it.
If the called function does not return any value, then control will jump backs to the
function call statement.
EXAMPLE -1 & 2
Trace the flow of execution for the following program:
1 5 1 2 3 4 8 print(a)
9 print(b)
1 5 6 7 1 2 3 4 8 9
EXAMPLE – 3 & 4 [2-MARKS]
Trace the flow of execution for the following program and predict output:
2 print("Hi") 2 print("Hi")
3 print("Hello") 3 print("Hello")
4 Test( ) 4 Test( )
5 print("Bye")
5 print("Bye")
6 Test( )
7 print("Thank You")
1 3 4 1 2 5
1 3 4 1 2 5 6 1 2 7
Hello
Hi
Bye
Hi
Thank You
EXAMPLE 5 & 6
Trace the flow of execution for the following program and predict output:
2 print("Hi") 2 print(a)
3 3 print("Hello")
6 print("Bye")
1 4 5 1 2 4 5 1 2 4 6 1 4 5 1 2 3 4 5 1 2 3 4 5 1 2 3 4
0
Hi Hello
Hi
1
Hello
2
Hello
EXAMPLE - 7
Trace the flow of execution for the following programs:
1 def Add( ):
2 a,b=10,20
3 print(a+b)
4 def Sub( ):
5 a,b=142,56
6 print(a-b)
7 def Mul( ):
8 a,b=7,5
9 print(a*b)
10 Add()
11 Sub()
12 Mul()
1 4 7 10 1 2 3 11 4 5 6 12 7 8 9
EXAMPLE - 8
Trace the flow of execution for the following programs:
1 def Square( ):
2 print("Hi this is Square()”)
3 Cube()
O/P:
4 print(“Bye“)
Hi Welcome
5 def Cube():
6 Rect() Hi this is Rect()
7 print(“Hi this is Cube()“)
8 def Rect():
9 Disp()
10 print(“Hi this is Rect()“)
11 def Disp():
12 print(“Hi Welcome“)
13 Rect()
1 5 8 11 13 8 9 11 12 10
EXAMPLE – 9 & 10
Trace the flow of execution for the following program and predict output:
1 def Cube( ):
1 def Cube(a):
2 return(a**2)
2 print(“Hi")
3
3 return(a**2)
4 a=2 a=100
4
5 Res=Cube(a) print(“Bye”)
5
6 print(“Result=“,Res) 6 a=45
7 print("Bye") 7 print(Cube(a))
8 print("Bye")
1 4 5 1 2 5 6 7
1 6 7 1 2 3 7 8
Result= 4
Hi
Bye
2025
Bye
EXAMPLE – 11 & 12
Trace the flow of execution for the following program and predict output:
1 def Power(b,p):
1 def Outer(a,b):
2 y=b**p
2 def inner(c,d):
3 return y
3 return c+d
4 return inner(a,b)
4
5 def Square(x)
5
6 a=power(x,2) 6 Outer(4,7)
7 return a
8
9 n=5 1 6 1 2 4 2 3 4
10 result=Square(n)
11 print(result)
1 5 9 10 5 6 1 2 3 6 7 10 11
O/P : 25
TYPES OF ARGUMENTS
In Python, If the function header has three parameters in its header then the function
call should also pass three values.
That is, the first parameter receives the value of first argument, second parameter
receives the value of second argument and so on...
Rules:
i. Number of arguments passed must match the number of parameters in the function’s
header.
Note:
If the number of positional arguments and the number of positional parameters don’t
match, then Python raises a TypeError exception.
Example of Positional Arguments
Example: Example – Output Not meaningful
def Disp(Name, age, City, Pincode): def Disp(Name, age, City, Pincode):
print("Your Name is:", Name) print("Your Name is:", Name)
print("Your Age is:", age) print("Your Age is:", age)
print("Your City is:", City) print("Your City is:", City)
print("Pin code is:", Pincode) print("Pincode is:", Pincode)
O/P: O/P:
Your Name is: Raj Your Name is: 110005
Your Age is: 35 Your Age is: Delhi
Your City is: Delhi Your City is: Raj
Pin code is : 110005 Pin code is : 35
Example of Possible Errors in Positional Arguments
Eg: 1 Number of Parameters not matching Eg: 3 : Weak in type binding
def Disp(Name, age):
def Disp(Name, age, City, Pincode):
print("Your Name is:", Name)
print("Your Name is:", Name)
print("Your Age is:", age+5)
print("Your Age is:", age)
#Error: Missing two
Disp('Raj', 35) positional arguments. Disp(35, 'Raj') #Error,
We cannot
Eg: 2 Parametrs name must not be duplicate concatenate
string with
#Error: Duplicate
integer.
Parameter.
def Disp(Name, age, Name, Pincode):
I.e. keyword arguments need not be in same order as the parameter listed in the
function definition.
Rules:
(i) Function definition Parameters name must match with keyword names in function call.
(ii) A positional argument cannot follow a keyword argument. I.e. Having a positional
arguments after keyword argument will result into error.
Example of Keyword Arguments
Example: O/P:
def Disp(Name, age, City, Pincode): Your Name is: Raj
print("Your Name is:", Name) Your Age is: 35
print("Your Age is:", age) Your City is: Delhi
Eg: 2 Parametrs name must not be duplicate: #Error, Disp() got an unexpected
keyword argument 'a'
#Error: Duplicate
Parameter. Eg: 4 : Positional argument should not
def Disp(Name, age, Name, Pin): Follow keyword arguments.
print("Your Name is:", Name) def Disp(Name, age, Pin):
print("Your Age is:", age) print("Your Name is:", Name)
print("Your Pin is:", Pin) print("Your Age is:", age)
Code=110005 #Error.
Disp(Name='Raj', age=35,City='Delhi',Pin=110005) Disp(Name='Raj', age=35,Code)
(iii) Default Arguments
The Default values are specified in the function header of function definition.
That is, the parameter having default value in the function header is known as
"Default Parameters/Arguments“.
(i) It is used in situation, Where some parameters always have the same value.
function call.
taken by Python).
Rules and Advantages of Default Arguments
Rules:
Any parameter cannot have a default value unless all parameters appearing on its right
have their default values. I.e. We must start to assign default value from right
parameter to left parameter.
Note: The default parameters values are considered only if no value is provided for that
parameter in the function call statement.
Advantages:
print(P1,P2)
print(P1,P2)
Disp(43,100)
Disp(43)
In the above example, Disp() passing only In the above example, Disp() passing
one argument to function definition. required arguments to function definition. So,
43 is assigned to formal Parameter P1 and 100
In this situation, Python will assign 43 to P1 is assigned to formal parameter P2 respectively.
and default value 20 to P2 whenever we are
not passing value for P2. Note: In this situation It will not assign
default value 20 to P2.
PRACTICE QUESTIONS
Find the output of the following codes:
print(n1,n2)
def Check(ch1,ch2):
if ch1==ch2:
Calc ()
return True
Calc (2,12)
else:
Calc (3)
return False
r=check('a', 'a‘)
O/P: O/P:
print(r)
True
1 3 Cube()
24 14 Cube is: 8
3 3 Cube(4)
Cube is: 64
(iv) Variable Length Arguments
Variable length parameters/arguments are used to take an unspecified amount of input
from function call.
The Non-keyword parameter acts like a "Tuple". Hence, we cannot modify or delete a
specific value of them.
Rules:
Syntax: Example:
def Emp(Name, *Other_Details):
def Function_name(pos_arg(s), *p2):
print("Your Name is:",Name)
Body of the function print(Other_Details)
Calling_function(arg1,arg2,arg3) Emp(‘Raj‘,35,‘Delhi‘,10000,'Mumbai'):
Keyword variable Length parameters/arguments
If we use two asterisk ('**') in front of the formal parameter name, then it is
called Keyword variable length argument(s).
The keyword parameter acts like a "Dictionary". Hence, we can modify or delete a
specific value of them. But, it is not reflect back to the original.
Rules:
Syntax: Example:
def Emp(Name, **Other_Details):
def Function_name(pos_arg(s), **kwargs):
print('Your Name is:', Name)
Body of the function print("Your Age is:",Age)
print("Your Birth City :",Born_City)
print("You're Working in :",Work)
Calling_function(key1=arg1,key2=arg2,key3=arg3)
Emp('Raj'Age=35, Born_City=‘Delhi‘,Work='Mumbai')
DIFFERENCE BETWEEN POSITIONAL AND KEYWORD ARGUMENTS
(i) We must pass argument(s) in exact order (i) We can pass argument(s) in any order,
in which the parameters are given in the with the help of their keyword No need to
function definition. remember position of the parameters available
in function header.
(ii) In Positional argument, Function definition (ii) In Keyword arguments, Function definition
parameter(s) name and function call parameter(s) name and keyword available in
argument names may or may not be same. function call must be same.
(iii) It is also called "Required Arguments" (iii) It is also called "Named Arguments".
(i) In positional arguments, we must pass required (i) In Default arguments, we may or may not pass
number of arguments to function definitions. required number of arguments to function
definitions.
(ii) In the absence of required number of (ii) In the absence of required number of
argument(s) during function call the Python argument(s) during function call the Python
will raise an 'TypeError‘. will assign default value to the parameter(s).(If
default value is available to the parameter).
(i) Keyword argument(s) are available in (i) Default arguments are available in function
function call. header.
(ii) We must pass required number of keyword (ii) We may or may not pass required number of
arguments to function header. argument(s) to function header. Because, in the
absence of required number of arguments,
python will assign default value to the
parameters.
(iii) Function definition Parameters name must (i) Function definition Parameters name may or
match with keyword names in function call. may not match with Default parameter’s
names in function call.(Suppose, if they passed
as argument)
(iv) We can assign value(s) to the keyword(s) in (iv) Any parameter cannot have a default value
any order during function call. unless all parameters appearing on its right
have their default values.
(v) Ex: def Interest(principal, time, rate): (v) Ex: def Interest(principal, time, rate=0.10):
Ex: Display(a or b)
Ex: Test(int(str(54))
Fun(float("52.5“)*2)
SCOPE OF VARIABLES
Variable Scope:
The Scope refers to the visibility and life time of a variable in a program/function.
Life Time:
The time for which a variable or name remains in memory is called Life time of a
variable.
We cannot access Local variables outside of the function. We can access them only
within the function. Because, Life time of the local variable ends when a function ends.
Ex-2:
Ex-1:
def Disp(): def Person(name, age):
A=20 Salary=10000
B=34 print(“Your Name is:",name)
print(“The value of A is:“,A) print("Your Age is:",age)
print(“The value of B is:“,B) print("Your Salary is:",Salary)
Disp( ) Person('Arun',45)
In the above example, function Person()
has totally Three local variables – name,
In the above example, function Disp() has
age and Salary.
totally Two local variables – Note:
The parameters of a function also
A and B.
considered local.
POSSIBLE ERRORS IN LOCAL VARIABLE
Ex-1: Ex-2:
Global variables can be access by any part of the program. I.e It can be accessed by
any function.
The life time of the global variable will remain till end of the program.
If any changes happens to the global variable it will reflect all parts of the program.
EXAMPLES OF GLOBAL VARIABLE
.
Disp( ) 2 2
R=2233 a=243
print("The value of Q is:",Q)
Disp( ) def Out( ):
print("The value of Q is:",Q) Y=130
print("The value of a is:",a)
LEGB Rule:
When we refer any variable name inside a function, Python Searches four scopes they
are:
ii. Enclosed (E) – We can define it inside the enclosing function (Nested function).
iv. Built-in (B) – These are the reserve name in the built-in modules of Python.
The above four rules is used to decide the order which the namespaces are to be
searched for name resolution or scope resolution.
How Python Resolve Naming Problems?
Step 1:
First variable name is checked in "Local Environment(L)" and if it is available then
it will be used. Otherwise, It will go to step 2.
Step 2:
Then Variable name is checked in "Enclosed Environment(E)"(Nested Function)
and if it is available then it will be used. Otherwise, it will go to Step 3.
Step 3:
Then Variable name is checked in "Global Environment(G)" and if it is available
then it will be used. Otherwise, It will go to Step 4.
Step 4:
Then Variable name is checked in “Built-in Environment(B)" and if it is available
then it will be used. otherwise it will go to step 5.
Step 5:
If variable name is not found in any of the above steps then Python will generate
an error message. (Ex: ‘age’ is not defined)
Case (i) Variable name in Local Scope
In this case, If the variable name is available with in the function(i.e. Local Scope) then
Python will use it.
Example 1:
def Disp():
A=1000
print("Value of A is:", A)
Disp()
o/p:
Value of A is: 1000
Case (ii) :Variable name in Enclosed Scope
In this case, If the variable name is available with in Enclosed Scope then Python will
use it.
Example 1:
def Outer():
A=1000
def Inner():
B=1500
print("Value of A is:", A)
print("Value of B is:", B)
Inner()
Outer()
o/p:
Value of A is: 1000
Case (iii):Variable in Global scope but not in
Local scope.
In this case, The variable is available in global scope not in local scope, So Python will
use global variable to solve name resolution.
Example 1: Example 2:
A=1000
A=1000
def Disp():
def Disp():
print("Value of A is:", A)
print("Value of A is:", A)
A=1500
Disp()
Disp()
o/p: o/p:
Value of A is:1000 Value of A is:1500
Case (iv): Same Variable Name in Local scope as well
as Global Scope.
In this case, If the variable names are same in local scope as well as in global scope,
then python will use only local variable of function.
Example 1: Example 2:
A=1000
def Disp(): def Disp():
A=2000 A=2000
print("Inside the function A=“,A)
print("Value of A is:", A)
A=1000
Disp()
Disp()
print("I am Using global A=", A)
o/p:
o/p:
Inside the function A=2000
Value of A is: 2000
I am Using global A=1000
Case (v):Variable in Built in Scope
If variable is not available in Local Scope or Enclosed Environment or Global scope then
Python will search in Built in environment to solve name resolution.
Example 1:
import math
def Disp():
print("pi value is:", pi)
Disp()
o/p:
pi value is:3.141592653589793
Case (vi):Variable neither in Global scope or in Local
scope or in Built – in scope
In this case, if the variable name is not present in neither in global or local scope or
built-in environment then python will report an error message.
Example 1: Example 2:
def Disp():
def Disp():
print("Value of B is:", B)
print("Value of A is:", A)
Disp() Disp()
print("Value of A is:", A)
o/p: o/p:
NameError: name ‘A' is not defined NameError: name 'B' is not defined
Purpose of global keyword in functions
(or)
How to use the global variable inside local scope?
If we want to assign or update the value of global variable inside of any function then
we must use global keyword in front of variable name inside of function.
To tell a function that for a particular name, do not create a local variable name but use
global variable instead we need to write: global variable_name
Example:
A=1000
def Disp():
gloabl A
A=A*3
Disp()
O/P:
The value of A is: 3000
Purpose of non local keyword in functions
(or)
How to use Inner function variable after it’s definition in outer function?
If we want to access inner function variable name after it’s definition inside of outer
function then we must define nonlocal variable in inner function(in nested function).
O/P:
420 80
PASSING MUTABLE/IMMUTABLE OBJECTS TO
FUNCTIONS
If we pass Immutable type of objects( Such as Integer, float, string and Tuples) as
arguments to function , then if any changes happens to the receiving parameters
inside of the function which is not reflect back to the original arguments.
x=10 120
y=20
O/P:
print("Before calling Disp()") Before calling Disp()
print("The value of x is:", x)
The value of x is: 10
print("The value of y is:", y)
The value of y is: 20
Disp( x, y) Inside of the function
print("After calling Disp()") The value of x is: 11
print("The value of x is:", x) The value of y is: 120
print("The value of y is:", y) After calling Disp()
The value of x is: 10
The value of y is: 20
EXAMPLE OF PASSING MUTABLE OBJECTS TO
FUNCTIONS
Example – 1: Main() Disp()
def Disp(L): Before calling Disp()
List=[1,2,3,4,5] L
List
print("Before calling Disp()")
O/P:
print("The value of List is:", List) Before calling Disp()
Disp( List) The value of List is: [1,2,3,4,5]
print("The value of List is:", List) The value of List is: [50,2,3,4,5]
List=[1] O/P:
print("Before calling Disp()") Before calling Disp()
The value of List is: [1]
print("The value of List is:", List)
Inside of the function
Disp( List)
After Adding some elments:[1,2,5,10]
print("After calling Disp()")
After calling Disp()
print("The value of List is:", List)
The value of List is: [1,2,10]
PRACTICE QUESTIONS
What is the output of the following programs?
def Fun2(L)
def Fun1(MyList) print("Inside Called Function Now")
print("Received List is:", L)
for i in range(len(MyList)):
new=[3,5]
if MyList[i]%2==0: L=new
MyList[i]/=2 L.append(6)
MyList[i]*=2 List1=[1,4]
print("List Before Function Call:", List1)
List1=[21,20,6,7,9,18,100,50,13]
Fun2(List1)
Fun(List1) print("List After Function Call:", List1)
print(List1) O/P:
List Before Function Call: [1, 4]
Inside Called Function Now
O/P: Received List is: [1, 4]
After Changes the List is: [1, 4]
[42, 10.0, 3.0, 14, 18, 9.0, 50.0, 25.0, 26] List After Function Call: [1, 4]
THE END