0% found this document useful (0 votes)
5 views

CH 3 - WORKING WITH FUNCTIONS

Chapter 3 introduces functions in programming, defining them as groups of related statements that perform specific tasks. It discusses the advantages of using functions, such as code reusability and improved readability, and categorizes them into built-in, module-defined, and user-defined functions. The chapter also covers the properties of user-defined functions, their creation, invocation, and the distinction between actual and formal parameters.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

CH 3 - WORKING WITH FUNCTIONS

Chapter 3 introduces functions in programming, defining them as groups of related statements that perform specific tasks. It discusses the advantages of using functions, such as code reusability and improved readability, and categorizes them into built-in, module-defined, and user-defined functions. The chapter also covers the properties of user-defined functions, their creation, invocation, and the distinction between actual and formal parameters.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 83

CHAPTER - 3

WORKING WITH FUNCTIONS


INTRODUCTION TO FUNCTION
Function:

 A function is a group of related statements that performs a specific task.

 Functions help to break our program into smaller and modular chunks.

(OR)

 A large program is divided into smaller units is known as "Function".


Which contains set of statements in it.
ADVANTAGES OF FUNCTIONS
 It is used to reduced length of the code.

 It supports reusability.

 It is used to increase the readability of the code.

 It is used to breaking up complex problems into smaller units.


TYPES OF FUNCTIONS
 Generally, Functions can be divided into three types they are:

Functions

Functions defined User defined


Built-In functions within Modules functions
(i) Built -In Functions
 Built-in functions are predefined functions, For built-in functions no need to
write code by yourself.

 The code/logic for these functions are already available in python library.

 We can call these functions in our program without defining them.

 Ex: len(), type(), input() etc...


(ii) Functions defined in Modules
 These functions are pre-defined in particular modules and can only be used
when corresponding module is imported by using "import".

 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

Function Definition:

 A function definition provides the actual body of the function. It contains

logic to perform specific task. It will be execute only when it is called.

 A function definition may or may not contains parameters.

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:

 Function header always ends with a colon ' : ‘.

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 :

Body of the function msg='India'


Function
print("Hi", msg) Body

Example 2:
Syntax 2: Parameters_name
keyword Function name

def function_name( p1,p2,p3): def Greet(name,msg): Ends with


colon :
Body of the function print("Hi" ,name)
Note: Where p1,p2,p3 are parameters. print("Welcome to" ,msg)

Function
Body
PRACTICE QUESTIONS [1 (or) 2 Marks]
From the following questions identify keyword, function name and parameters
name.
Q.no 1: Answer:

def Square( ): Keyword -> def


a=2 Function name -> Square
print(a**2) No
Parameter(s) name ->
parameter(s)
Answer:
Q.no 2:
Keyword -> def
def add( x,y): Function name -> add
print(x+y) Parameter(s) name -> x, y
PRACTICE QUESTIONS [1 (or) 2 Marks]
From the following questions how many function definitions are available and
identify their keyword, function name and parameters name.
Answer:
Q.no 1:
Keyword -> def
def Thrice( ):
Total.no of definitions -> 1
v=2
print(v*3) Function name -> Thrice
Parameter(s) name -> No parameter(s)
Answer:
Q.no 2: Keyword -> def
def Sub(x,y): Total.no of definitions -> 2
print(x-y) Function name 1 -> Sub
Function name 2 -> Mul
def Mul( p,q,r):
Function 1 Parameter(s) -> x,y
print(p*q*r)
Function 2 Parameter(s) -> p,q,r
Invoking/Calling a user defined function
 After defining a function(s), a function should be invoke/call by using its
name. A function may or may not be call with argument(s) or without
Example 1:
argument(s).
def Square( ):
Syntax 1: a=2
print(a**2) Calling/Invoking
function_name( ) Square() without
Square( ) parameter(s).

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)

(iv) Calling a function inside of another statement as argument to function


call.
Ex:
print( Add(2,3) )

(v) Calling a function inside of expression as argument to function call.

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.

 It is also known as "Arguments“.

Formal Parameters:

 Formal parameters are available in function header, which is used to receive


value from actual Parameter.
Formal Parameter(s)/
Parameters
 It is also known as “Parameter(s)”

Actual Parameter(s) / Argument(s)


CATEGORIES OF USER DEFINED FUNCTION
 A user can write the user defined function in four different ways they are:

(i) Function with no parameter and no return value.


void functions
(ii) Function with parameter and no return value.

(iii) Function with parameter and with return value.


Non - void functions
(iv) Function with no parameter and with return value.

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.

 To return value(s) from the function we must use ‘return’ keyword.

 Once the return keyword is found in function definition, after executing

that return statement, the control will transfer immediately to the

calling function.

 If return statement is not used inside the function, the function will return

‘None’ object.
RETURNING SINGLE VALUE FROM THE FUNCTION

 The ‘return’ keyword is used to return a 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

(i) Returning as literal: Example 1 Example 2


[Example 1: A literal being returned] def Disp( ): def Disp( ):
[Example 2: An expression return 5 return 5+4

involving literal being returned] print(Disp()) R=Disp()

(ii) Returning as Variable: Example 1 Example 2


def Disp( ): def Disp( ):
[Example 1: Variable being returned]
a=5 a=5
[Example 2: Expression involving
return a return a**3
variable and literal being returned] print(Disp()) V=Disp()
(iii) Returning an expression: Example 1 Example 2
def Disp( ): def Disp(a,b,c ):
[Example 1 and 2: Expression Involving a,b,c=5,1,2 return a+b/c
variable being returned]
return a+b/c
S=Disp(1,2,3)
print(Disp()) print(S)
RETURNING MULTIPLE VALUES FROM THE FUNCTION

 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:

(i) Using tuple.


(ii) Using list.
(iii) Using dictionary.
EXAMPLE FOR RETURNING MULTIPLE VALUES

(i) Using tuple: Example 1 Example 2


def Disp( ): def Disp( ):
return(5,1,“A”,34.4) a,b,c,d=5,1,”A”,34.4
return a,b,c,d
w,x,y,z=Disp() # Assign returned tuple
print(Disp( )) # Displaying returned items as tuple
(ii) Using List: Example 1 Example 2
def Disp( ): def Disp( ):
return [5,1,2,”A”,34.5] a=[5, "Apple","Orange"]
return a
p,q,r,s,t=Disp( ) # Assign returned List print(Disp()) # Displaying returned items as List
Example 1
(iii) Using Dictionary def Disp( ):
d = dict()
d [1]=‘Raj’
d [23]=‘Ram’
return d
print(disp())
EXAMPLE PROGRAM

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.

Q.no 2: Correct Code: Error 1 – Every Parameter must


separate with commas.
def Dollars(p.q.r): def Dollars(p,q,r):
Error 2 – It must be q or x
print(p,x,r) print(p,q,r) must be defined.

Error 3 – Function Call should be Dollars.


Dollar(1,2,3) Dollars(1,2,3 )
PRACTICE QUESTIONS [2 Marks]
Find out the error(s) in the following program:
Q.no 3: Correct Code: Error 1 – Function name
cannot be a keyword.
def yield( ): def Yield( ):
a=500 a=500
print(a) print(a)
Error 2
yield( ) Yield( )

Q.no 4: Correct Code: Error 1 – Every Parameter must


separate with commas.
def F(p.q.r): def F(p,q,r):

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())

Q.no 6: Correct Code:

def Find(X,Y): def Find(X,Y):

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

 Flow of execution refers to the order in which statements are executed

during a program run.

Structure of Function in Python:


FLOW OF EXECUTION IN FUNCTION CALL
 Generally, all function definitions are given at the top, followed by statements
which are not part of any functions.

 Those statements which are not part of any function are called
“top level statements”. These top level statements are part of the main program.

 Whenever a function call statement is encountered , an “Execution Frame” for the


called function is created and the control transferred to it.
EXECUTION FRAME
An execution frame contains the details of the following:

 Some internal information(Used for debugging)

 Name of the function.

 Values passed to the function.

 Variables created within function.

 Information about next instruction to be executed.


GUIDE LINES TO EXECUTE FUNCTION
 Execution always begins at the first statement (i.e. Line 1) of our program.

 Statements are executed one at a time in order from top to bottom.

 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 def Disp(): 1 def Square( ):


2 x=200
2 a=2
3 y=250
3 b=3
4 print(x*y)
4 print(a,b)
5 a=100
5 Disp( )
6 b=200
7 Square()

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:

1 def Test( ): 1 def Test( ):

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:

1 def Test( ): 1 def Disp(a):

2 print("Hi") 2 print(a)

3 3 print("Hello")

4 for i in range(2): 4 for i in range(3):


5 Test( ) 5 Disp(i)

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.

 Python supports following types of formal arguments/parameters:

(i) Positional arguments / Required arguments.

(ii) Keyword arguments/ Named arguments.

(iii) Default arguments.

(iv) Variable length arguments.


(i) Positional Arguments / Required arguments.
 In Positional arguments, when we call a function we must pass argument(s) in the
exact order in which the parameters are given in the function definition.

 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.

ii. Parameters name should not be duplication in function 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)

Disp(‘Raj’, 35, 'Delhi‘, 110005) Disp(110005, 'Delhi‘, 'Raj‘,35)

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):

print("Your Name is:", Name)


print("Your Age is:", age)

Disp('Raj', 35,'Delhi‘, 110005)


(ii) Keyword Arguments
 In Keyword arguments, we can pass argument(s) in any order during function call , No
need to remember position of the parameters available in function header.

 I.e. keyword arguments need not be in same order as the parameter listed in the
function definition.

Syntax to call a function using keyword argument(s):

Function_name(pos_arg(s), keyword1=arg1, keyword2=arg2 ,…)

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

print("Your City is:", City) Pin code is : 110005

print("Pin code is:", Pincode)

Disp(Pincode=110005, City='Delhi', Name='Raj' ,age= 35)


Example of Possible Errors in Keyword Arguments
Eg: 1 Number of Parameters not matching: Eg: 3 : Keyword Mismatching in Disp()

def Disp(Name, age, City, Pin): def Disp(Name, age):


print("Your Name is:", Name) print("Your Name is:", Name)
print("Your Age is:", age)
#Error: Missing print("Your Age is:", age+5)
Disp(Name='Raj', age=35) two positional
arguments. Disp(a=35, Name='Raj')

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“.

 Uses of Default Parameters/Arguments:

(i) It is used in situation, Where some parameters always have the same value.

(ii) It is used in situation, in the absence of required number of arguments during

function call.

(I.e. Whenever user not passed required number of arguments to function

definition, then assigned default value of parameter is automatically

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:

 They can be used to add new parameters to the existing functions.

 They can be used to combine similar functions to one.


Legal/ Illegal Function headers with default values

Legal Function headers with default values:

(i) def Disp(P1,P2=20) : (ii) def Disp(P1=34.5,P2=2,P3=12) :

Illegal Function header with default values:

(i) def Disp(P1=20,P2):

(ii) def Disp(P1=20,P2,P3=34):

(iii) def Disp(P1=20,P2=54.4,P3):


Examples of Default Arguments
Example 1: Example 2:

def Disp(P1,P2=20) : def Disp(P1,P2=20) :

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:

def Calc(n1=1,n2=1): def Cube(num=2):


n1=n1*n2 C=num**3

n2+=2 print(“Cube is:“,C)

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.

 We can specify variable length parameters/arguments by using '*‘.

 Two types of variable length arguments are available in Python:

(i) Non – Keyword Variable Length arguments.

(ii) Keyword variable Length arguments.


Non- Keyword variable Length parameters/arguments
 If we use only one asterisk ('*') in front of the formal parameter name, then it is
called Non-Keyword variable length argument(s).

 The Non-keyword parameter acts like a "Tuple". Hence, we cannot modify or delete a
specific value of them.

Rules:

 Positional arguments should not follow variable length arguments.

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:

 Positional arguments should not follow variable length arguments.

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

POSITIONAL ARGUMENTS 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".

(iv) Ex: (iv) Ex:


def Disp(Name, age,City): def Disp(Name, age, City):
print("Name:", Name) print("Name:", Name)
print("Age:",age) print("Age:",age)
print(“City:", City) print("City:", City)

Disp('Raj‘, 36, 'Delhi‘) Disp(age=36, City='Delhi', Name=‘Raj’)


DIFFERENCE BETWEEN POSITIONAL AND DEFAULT ARGUMENTS
POSITIONAL ARGUMENTS DEFAULT 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).

(iii) Ex: (iii) Ex:


def Circle(r,pi): def Circle(r, pi=3.14):
Area=pi*(r**2) Area=pi*(r**2)
print(“The Area of Circle is:“, Area) print(“The Area of Circle is:“, Area)

Circle(5, 3.14) Circle(5)


Circle(56.2, 3.14) Circle(56.3)
DIFFERENCE BETWEEN KEYWORD AND DEFAULT ARGUMENTS
KEYWORD ARGUMENTS DEFAULT ARGUMENTS

(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):

print(principal, time, rate) print(principal, time, rate)


Interest(rate=0.12, principal=5400, time=2) Interest(5400,2)
COMPOSITON
 Composition is generally referred to using an expression; or a statement as part of larger
statement.

 The arguments of a function call can be any kind of expressions:

(i) Passing Arithmetic Expressions as arguments:

Ex: Disp1( (4+5), (6*2))

(ii) Passing Logical Expression as arguments:

Ex: Display(a or b)

(iii) Passing converted type as arguments:

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.

 In Function, we can define a variable in two scopes they are:

(i) Local Variable/Scope.

(ii) Global Variable/Scope.


(i) LOCAL VARIABLE
 Any variable which is defined within a function is called “Local Variables“.

 The parameter(s) of a function also called Local to that function.

 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:

def Disp(): Local Variable ‘A’ def Person(name, age):


A=20 Salary=10000
print(“Your Name is:",name)
print(“The value of A is:“,A)
print(“Your Age is:“age)
Disp():

print(“The value of A is:“,A) Person('Arun',45)


#Error 1 & 2:
print("Name:",name)
name and age are
#Error: print(“Age:",age) consider as local
A is Local to that function.
Variable to print(Salary) So we cannot
function Disp. access it outside
So we cannot of the function.
access it outside Error 3:
of the function. Salary is Local to
Person(). So we
cannot access it
outside.
(ii) GLOBAL VARIABLE
 Variables declared outside of any functions are called “Global variables”.

 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
.

Ex-1: Ex-2: Ex-3:


1 1 1
Q=23 Q=23 b=23

def Disp( ): def Disp( ): def In( ):


A=100 X=1000
print("The value of Q is:",Q) print("The value of Q is:",Q) print("The value of b is:",b)

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)

In the above example, print("The value of a is:",b)


S='Yes' 3
1 is Global variable In the above example,
In( )
1 are Global variables. Out( )
2 In the above example,
1
2 are Global variables.
3
NAME RESOLUTION OR LEGB RULE
 When we access a variable from within a program or function, Python follows name
resolution rule or LEGB rule.

LEGB Rule:

 When we refer any variable name inside a function, Python Searches four scopes they
are:

i. Local (L) – We can define it inside the function.

ii. Enclosed (E) – We can define it inside the enclosing function (Nested function).

iii. Global (G) – We can define it at the uppermost level.

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()

print(“The value of A is:“)

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?

 nonlocal keyword is used in Nested functions(I.e. in Enclosed Environment).

 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).

 Syntax: nonlocal variable_name

Ex 1: (Without nonlocal keyword) Ex 2: (With nonlocal keyword)


def Outer(): def Outer():
X="John" X="John"
def Inner(): def Inner():
X="Hello"
nonlocal X
Inner() X="Hello"
print(X) Inner()
print(X)
Outer()
Outer()
o/p: o/p:
John Hello
PRACTICE QUESTIONS
What will be the output of the following programs?

Q.No : 1 Q.No : 2 Q.No : 3

def Check(): a=100 X=100


global num def Show(): def Change(P=10,Q=25):
num=1000 global a global X
print(num) a=200 if P %6==0:
def Invoke(): X+=100
num=100
print(num) global a else:
check() a=500 X+=50
print(num) show() Sum= P+Q+X
invoke() print(P, '#‘, Q , '$‘, Sum)
O/P: print(a)
100 Change() O/P:
1000 O/P: Change(18,50) 10 # 25 $ 185
1000 18 # 50 $ 318
500 Change(30,100) 30 # 100 $ 480
Q.no - 4

O/P:

420 80
PASSING MUTABLE/IMMUTABLE OBJECTS TO
FUNCTIONS

 In Python, We can pass Mutable and Immutable objects/ variables to functions.

 (i) Numbers, Strings and Tuples - Immutable types

(ii) List, Dictionary and Set - Mutable types.

 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.

 If we pass mutable type of objects(Such as List, Dictionary and Set) as arguments to


function ,then if any changes happens to the receiving parameters inside of the
function which is reflect back to the original arguments.
EXAMPLE OF PASSING IMMUTABLE OBJECTS TO
FUNCTIONS
Example – 1: Inside of Main() Inside of Disp()
def Disp( x, y): X 10 X 10
print(“Inside of the function“)
x=x+1 11
y=y+100
print("The value of x is:", x)
Y 20 Y 20
print("The value of y is:", y)

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()

print(“Inside of the function“)


1 2 3 4 5
L[0]=50
L
print("The value of List is:", L) List After calling Disp()
50 2 3 4 5

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("After calling Disp()") Inside of the function

print("The value of List is:", List) The value of List is: [50,2,3,4,5]

After calling Disp()

The value of List is: [50,2,3,4,5]


EXAMPLE OF PASSING MUTABLE OBJECTS TO
FUNCTIONS
Example – 2: When , 1
List=[1]
def Disp(L):
print(“Inside of the function“) When , 1 2
L.append(2)
L.append(2)
L.extend([5,10]) When , 1 2 5 10
print(“After adding some elements“, L) L.extend([5,1])
L.remove(5)
print(“After Remove the List is: “, L) When , 1 2 10
L.remove(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)

else: print("After Changes the List is:", L)

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

You might also like