0% found this document useful (0 votes)
7 views43 pages

Understanding Python Functions Basics

Uploaded by

aaryan.kaliya100
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)
7 views43 pages

Understanding Python Functions Basics

Uploaded by

aaryan.kaliya100
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

WORKING WITH FUNCTIONS

Topics to be covered
1. Introduction
2. Types of Functions
3. Create User Defined Function
4. Arguments And Parameters
5. Default Parameters
6. Positional Parameters
7. Function Returning Values
8. Flow of Execution
9. Scope of Variable

1|Page
FUNCTIONS: Function can be defined as a named group of instructions that accomplish a specific
task when it is invoked. Reusable block of code that performs a specific task. For example: len(), print(),
min(), max(), sorted () , type() etc.
Therefore:
• Set of instructions
• Specific task or related task
• Executed when call
• Data can be passed to a function
• Function can return data

• ADVANTAGES OF USING FUNCTIONS


▪ Increases readability
▪ Reduces code length
▪ Increases reusability
▪ Modularity

Functions are 2 types


1. Calling - which contains call statement, which calls a functions
2. Called - which is called

Calling Control shifts back to the


When
system calling function
executes
the call Control shifts from calling
statemen To called
t When we
give the
Called Call
statement
When called functions
Gets over or there is a
return statement
Q When a function is known as Calling Function?
A If a function contains a call statement then it is known as a calling function.

Q what is a call statement?


Ans: A statement given to shift the control to another function is known as call statement

2|Page
import math System shift control from this
program to the module which being
a=25 called
b=[Link](a)
Calling sqrt() in math
module

Call statement

import random
a=[Link](1,4)

Calling randint() from


random module

Call statement
Q What is the meaning of shifting control?
Ans When the CPU changes the registers, variables, executable statements etc, CPU sets an
environment for execution of the function. Eg saves environment of calling before shifting to
called function. When returning from the called function, releases the environment of the called
function. Recalls the environment of calling function
Q How does the system execute your program?
Ans main() is an auto executable function, if the program has main CPU starts the execution
from main()

3|Page
Calling Control shifts back to
If calling
function the calling function
passes the
data it Control shifts from calling
called To called
When we
give the
Called Call
statemen
When called
functions
Data is give to
calling
Q What will happen if the program does not have itmain()?
is called
Ans program will not be executed. Program will interpreted or compile but, In Python there is no
main() function it’s main program which we write in column 1, outside a function(S)

How to write a user defined function


def function name(parameter(s)): parameter or parameters → optional
“”” doc string”””
Statement(S)
return → optional

Comment are of 2 types


1. Single line #
#my first program print(“hello World”)
2. Multiline comment “”” “”” or ‘’’ ‘’’
When multi line comment in a functions and use it like help of the function it is called docstring
Docstring - is the first line of the function just after the function header

def func():
“”” this is my program
This is a new program
“””
Rules of writing docstring
1. function description
2. Syntax of the call statement of the function
3. Parameter and purpose
4. Data type of parameter
4|Page
5. Named or keyword parameters
6. Return

First multi line comment


of the function is called
docstring

def func():
""" This is new function
this function is a trial function
Can be displayed using
made by students of class 12 A"""
help() or function.__doc__
print("hello")
print(func.__doc__)
print(help(func))

Remember
1. __doc__ : displays docstring of the function
2. __name__ : displays name of the function
3. Program execution main part or main function

def func():
""" This is new function Main part of
this function is a trial function the program
made by students of class 12 A"""
print("hello")

print(func.__doc__)
print("name of my function is ",func.__name__) Execution of the
program starts form
the main part of the
main function is a function whose name is program
main If there is no main
def main(): part program will
not be executed

Python and Only Python you can define a function inside


another function
def fun():
def fun1(): → function inside a function
5|Page
Predefined function
a) built-in functions - Built-in functions are the ready-made functions in Python that are frequently used
in programs. We don’t have to import any module to use these functions.
• len
• range()
• Calculation
• sum
• max
• min
• abs
• Conversion function
• int()
• float()
• list()
• tuple()
• dict()
• str()
• Built-in modules
• math
• ceil
• floor
• sqrt
• fabs
x=-9.7
print([Link](x)) output 9.7
6|Page
• pow same **
x=[Link](7,2) is same x=7**2
• log, log10, sin. Cos, tan
• factorial
• random
• random
• randint
• randrange
• uniform
x=[Link](10,15)
Random in floating point >10 and <15
• choice and shuffle - any data from list of its own choice, shuffle the list
[Link](L)
• statistics
• mean
• median
• mode
How to import a module
A module is a file containing Python definitions (i.e., functions) and statements. To use these modules in the
program, a programmer needs to import the module by using either the import statement or the from
statement.
1. Import modulename
• Complete module will be imported, All the function in the module, Call function using module name
Eg
import math
a=[Link](25)
2. Using from
o function(s) can be imported, Directly function can be used, Only function(s) will be imported
o All the function of that module use *
Eg
from math import sqrt,ceil
a=sqrt(25)
b=ceil(4.5)
• Give an Alias at time of importing
import math as M

Use M in place of math


a=[Link](25)
Once alias Python suppress the original name
• from math import *
This will import all the function math module

7|Page
Some functions from math module are:
Name of Description Example
function
ceil (x) It returns the smallest integer not less [Link](-45.17) -45.0
than x, where x is a numeric expression. [Link](100.12) 101.0
[Link](100.72) 101.0
floor (x) It returns the largest integer not greater [Link](-45.17) -46.0
than x, where x is a numeric expression. [Link](100.12) 100.0
[Link](100.72) 100.0
fabs (x) It returns the absolute value of x, where [Link](-45.17) 45.17
x is a numeric value. [Link](100.12) 100.12
[Link](100.72) 100.72
pow (x, y) It returns the value of xy, where x and y [Link](100, 2) 10000.0
are numeric expressions. [Link](100, -2) 0.0001
[Link](2, 4) 16.0
[Link](3, 0) 1.0
sqrt (x) It returns the square root of x for x > 0, [Link](100) 10.0
where x is a numeric expression. [Link](7)
2.6457513110645907
Some functions from statistics module are:

Name of the Description Example


function
mean(x) It returns arithmetic mean >>>[Link]([11,24,32,45,51]) 32.6
median(x) It returns median (middle >>>[Link]([11,24,32,45,51]) 32
value) of x
mode(x) It returns mode (the >>>[Link]([11,24,11,45,11]) 11
most repeated value) >>>[Link](("red","blue","red")) red
Q What is the meaning of
1. Declaring a function
2. Defining a function
3. Calling a function
Ans
Declaring a function - telling the compiler about the function, first hand information is declaration
of a function(PYTHON doesn’t need declaration)
USER Defined Function
Defining a function - function is written,
def functionname():
-----
-----
-----
This is called definition of the function
8|Page
The block of statement inside function will be executed when the function is called or
invoked
Definition of the function has:-
• Function header with def keyword
• Full form of def is define
• Function name which is an identifier
• Parameter list in (), if any
• colon(:)
• statement(s) which you want to execute when that function is called
• May or may not return statement
def Func():
print(“hello”)
print(“how are you!!”)

As the definition of the function is written before calling the function, there is no need to
declare
Calling the function- to call the function for execution, a function will be called only when the
system encounters a call statement.
Where do we write a call statement???
Ans
Below the definition of function any where in the program
What is the function called where you give this statement?
Ans calling function

9|Page
def func1():
1
print("hello")
def func2(): 2
func1()
print("how are you")
def func3(): 3
Execution of
func2() the program
starts from
print("bye")
func3() 4
Known as main program

Hello
How are you
bye

1. def func1(): Execution


2. 9→ 6→ 7→ 3→ 4 → 1→ 2 → 5
print("hello")
→ 8 → 10
3. def func2():
4. func1()
5. print("how are you")
6. def func3():
7. func2()
8. print("bye")
9. func3()
10. print("see you!")

Called function returns back to its calling function


func1() → returns to func2()
func2() → return to func3()
func3() → return main program

10 | P a g e
Format 2: Parameter and no return
Calling give data to called function is known parameter or argument passing
Argument or parameter are of 2 types:
1. Actual parameter - the parameter in the call statement, Calling function, These are the
values passed to the function when it is called/invoked.
2. Formal parameter - the parameter or argument in the header of the calling function is
known as formal parameter, These are the values provided in Parenthesis when we
write a function Header.
def display(n): Formal parameter
In header of called function
a=10
display(a) When the function called data is
passed from actual parameter to
formal parameter

Actual parameter
In the call statement of calling
function

Example:
def area_of_circle(radius ): # radius Formal Parameter OUTPUT
print (“Area of circle = “,3.1416*radius*radius) Enter radius of circle 10
Area of circle = 314.16
r=int (input (“Enter radius of circle”))
ar=area_of_circle(r) # r - Actual Parameter or Argument

def display(n): def display(n):


print (n) print(n)

a=10
display(a) display(10)

Passing a variable Passing a value


It is called actual parameter It is called actual argument

But Formal parameter must be a variable


def display(20):
print(“value is 20”)

11 | P a g e
a=10
display(a)
Assign 10 to 20 is WRONG or INVALID because formal parameter must be a variable
because a value is assigned to a variable not to constant or literal

If Actual parameter is mutable data type then changes made formal parameter
will be reflected in actual parameter
a=10
a=20

Passing Arguments in Python


Function argument can be of 4 types
1. Required argument or positional argument
2. Keyword argument or named argument
3. Default argument
4. Variable length

1. Positional - The function call statement must match the number and positional order
of arguments as defined in the function definition, then it is called the positional
parameters.
Example:
def Test(x,y,z): # x,y,z are positional parameters
Then we can call function using following statements p,q,r=3,4,6 Test(p,q,r) #3
variables are passed
Test (4, q,r) # 1 literal and 2 variables are passed

12 | P a g e
def check(x,y,z):
Data of a will be given to x, b
to y, c to z

check(a,b,c)

Number of parameters passed in the call statement must match with no of


parameter in header of called function

The actual parameter must match with formal parameter

def display(age,name):

display(name,age)

Value of name will be copied onto age and value of age will be copied onto name
Remember
1. You must know the sequence of the formal parameter
2. You must know number of formal parameter because actual can neither more
than formal nor less than formal

Example
def sum(a,b,c):
s=a+b+c
print(s)

sum(x,y,z)
sum(2,3,4)
sum(2,y,3)
sum(2,3,z)
sum(x,3,4)

As there 3 variables in formal parameter so, we need 3 values for calling this function

The number of actual parameters passed in the call statement matches with the
number of parameters in the header of the called function.

13 | P a g e
As Python is not data type bound, data type may vary but number cannot vary
def display(A):
print("data:",A)

display("Hello Friends") # pass a string


display([1,2,4,5]) #pass a list
display((1,2,3,4)) #pass a tuple
display({"a":12,"b":45}) #pass a dictionary
display(45) #pass a integer value
display(78.6) #pass a float value

2. Keyword or Named parameter


passing the argument by using the parameter names during the function call.
Eg
print() function have named parameter
- sep
- end
print(1,2,3,end=”&”,sep=”$”)
print(4,5,6,sep=”&”,end=”@”)
aIn Python, keyword arguments, also known as named arguments, are a way to pass
arguments to a function by explicitly specifying the parameter name along with its
value.
def my_function(name, age, city):
print(name, age, city)

# Keyword arguments
my_function(age=25, city="London", name="Bob")
Keyword-only arguments mean whenever we pass the arguments(or value) by their
parameter names at the time of calling the function in Python in which if you change
the position of arguments then there will be no change in the output.

Benefits of using Keyword arguments over positional arguments

● On using keyword arguments, you will get the correct output because the order
of argument doesn't matter provided the logic of your code is correct. But in the
case of positional arguments, you will get more than one output on changing the
order of the arguments.

Difference between the Keyword and Positional Argument

14 | P a g e
Keyword-Only Argument Positional-Only Argument

Arguments are passed in the order of


Parameter Names are used to pass the
parameters. The order defined in the order
argument during the function call.
function declaration.

Order of parameter Names can be


Order of values cannot be changed to
changed to pass the argument(or
avoid the unexpected output.
values).

Syntax : -
Syntax :-
FunctionName(paramName=value,...)
FunctionName(value1,value2,value3,....)

def display(name,age,subject):

What will happen if we give the following call statement?


display(“Computer science”,”Ajay”,18)
Ans
name will get value as “Computer Science”
Age will get “Ajay”
Subject will get 18

Use formal parameter as keyword for passing the data


display(subject=”Computer Science”,name=”Ajay”,age=18)

def Display(Rollno,Name):
print("Your Rollno is ",Rollno)
print("Your Name is ",Name)

R=int(input("Enter Rollno:"))
N=input("Enter Name:")
Display(Name=N,Rollno=R)

15 | P a g e
Example
def Interest(P,R,T):
I=P*((1+R/100)**T)
print("Interest:",I)
Interest(4,2,2000) #where P=2000,R=4%,T=2year
Interest(R=4,T=2,P=2000)
Interest(P=3000,T=2,R=3)
Problem???
P=4,R=2,T=2000

Q what will happen in the following situations?


a. Interest(P=2000,R=3)?
Error??
No of parameters are not matching as formal parameters are 3 whereas call
statement only 2 values
b. Interest(2,3,P=2000)?
Error???
P=2,R=3, no value to T?

c. Interest(R=3,P=3000,5)
Error??
All the parameters must be keyword
Combination of keyword and positional is not allowed
3. Default parameter
- Values given to formal parameters
- Rightmost parameter towards left
- If the actual parameter is missing then instead of error it will consider the
default parameter
- The parameters which are assigned with a value in function header while
defining the function are known as default parameters. If no value is provided in
function call, then the default value will be taken by the parameter.
Example:
def SICal(amount, rate, time=10): #time has default parameter
- NOTE: Default parameters will be written in the end of the function header,
which means positional parameter cannot appear to the right side of default
parameter.

16 | P a g e
Example
def sum(a,b,c):
s=a+b+c
print(s)
To call you must give 3 value to call this function
Can call like
sum(1,2,3)
sum(x,y,z)
sum(1,y,z)
If you will less than 3 it will give an error, This problem solved by providing default
value
def sum(a=10,b=20,c=30):
s=a+b+c
print(s)
Now this function can be called:
No parameter a=10
sum() b=20
All 3 will get default value c=30
1 parameter a=11
sum(11) b=20
a will value from actual parameter whereas b and c will get c=30
default values
2 parameter a=11
sum(11,12) b=12
a will get 11, b will get 12 and c will get default value c=30
3 parameter a=11
sum(11,12,13) b=12
a will get 11, b will get 12, c will 13 c=13
Default values will be suppressed
Default value if only if actual parameter is not providing any value, but actual
parameter is providing the value then default values are suppressed( when value is
missing in call statement)
Q Consider the following function
def Interest(P=3000,R=2,T=3):
I=(P*R*T)/100
print(I)
What will happen when you give the following call statement(s):
1. Interest()
17 | P a g e
It give default values to P,R,T
P=3000, R=2,T=3
2. Interest(5000)
It give 5000 to P, R and T will get default values
P=5000, R=2, T=3
3. Interest(5000,4)
It gives 5000 to P, 4 to R and T will get default value
P=5000, R=2, T=3
4. Interest(5000,4,5)
It gives 5000 to P, 4 to R, 3 to T
P=5000, R=4, T=3
5. Is it possible to give R and T and giving default value
Interest(__, 4, 5)
Ans
Interest(R=4,T=5)
Remaining parameters will automatically get default value
6. What will happen if you give
Interest(7000,T=4)
P=7000,R=2,T=4
7. What will happen if you give
Interest(4,R=3,5)
P=4,R=3,T=5
8. What will happen if you give
Interest(7000,T=4,5)
Error
P=7000
T=4
T=5
Remember:
Positional parameter can be given before keyword or named parameter
Interest(7000,T=2) # correct
Interest(R=5,P=4000,5) #error
Named will be given after positional or positional is given before named
Consider the following function:
def function(a,b,c):
s=a+b+c
print(s)
Which of the following statement is incorrect, justify your answer
1. function(1,2) incorrect 3 parameters are required to call the function
18 | P a g e
2. function(a=1,c=2,b=3) correct
3. function(4,c=4,b=6) correct
4. function(c=5,b=3,15) incorrect no value is provided to a, if the function header is def
function(a=4,b=6,c=7) then there is no error
5. function(5,b=4,7) incorrect function(5,4,7), positional cannot after named
parameter
6. function(5,c=6,b=11) correct
Example 1:
#Menu driven program
def check1(n):
if n==0:
print("the number is zero")
elif n%2==0:
print("The number is even")
else:
print("the number is odd")
#------------------------------------------------------------
def check2(n):
if n==0:
print("the number is zero")
elif n>0:
print("the number is positive")
else:
print("the number is negative")
#---------------------------------------------------------
def Multiple(n):
print("First five multiples:")
for i in range(1,6):
print(n*i,end="\t")
print()
#-------------------------------------------------------
while True:
print("""1. Find the number is even or odd
2. Find if the number is positive or not
3. Find First 5 mutliple of number
4. Exit""")
ch=int(input("Enter your choice:"))
19 | P a g e
if ch in [1,2,3]:
a=int(input("Enter the number:"))
if ch==1:
check1(a)
elif ch==2:
check2(a)
elif ch==3:
Multiple(a)
elif ch==4:
break
else:
print("Invalid choice")

Example2:
#Menu driven program
def check1(n):
if n==0:
print("the number is zero")
elif n%2==0:
print("The number is even")
else:
print("the number is odd")
#------------------------------------------------------------
def check2(n):
if n==0:
print("the number is zero")
elif n>0:
print("the number is positive")
else:
print("the number is negative")
#---------------------------------------------------------
def Multiple(n):
print("First five multiples:")
for i in range(1,6):
print(n*i,end="\t")
print()
#-------------------------------------------------------
20 | P a g e
while True:
print("""1. Find the number is even or odd
2. Find if the number is positive or not
3. Find First 5 mutliple of number
4. Exit""")
ch=int(input("Enter your choice:"))
if ch==1:
a=int(input("Enter the number:"))
check1(a)
elif ch==2:
a=int(input("Enter the number:"))
check2(a)
elif ch==3:
a=int(input("Enter the number:"))
Multiple(a)
elif ch==4:
break
else:
print("Invalid choice")
def Add_list():
e=int(input("enter data to add"))
[Link](e)
print(L)
def Del_list():
e=int(input("enter data to delete"))
[Link](e)
print(L)
def Duplicate():
[Link]()
for i in range(len(L)):
for j in range(i+1,len(L)):
if L[i]==L[j]:
print(L[j])
def Search():
e=int(input("enter data to search"))
if e in L:
print("found")
else:

21 | P a g e
print("not found")

L=eval(input("Enter a list"))
while True:
print("""
1. Add in list
2. Remove from List
3. find duplicate
4. Search in list
5. Exit""")
ch=int(input("Enter your choice"))
if ch==1:
Add_list()
elif ch==2:
Del_list()
elif ch==3:
Duplicate()
elif ch==4:
Search()
elif ch==5:
break
else:
print("invalid choice")
4. Arbitrary argument
- Number of arguments
- Type of arguments

def fun(*L):
- Creates a tuple of all the arguments as formal parameter
- Number of actual argument is not fixed, formal parameter will be tuple having data
depending upon the actual parameters passed

def func(x,y,z): def func(*ag):

How many arguments I should in the How many arguments I should in the actual
actual parameter to call the above parameter to call the above function?
function? Ans
Ans Minimum =1
22 | P a g e
Maximum is 3 Maximum =any number
Possible
func(1,2,3) How many formal parameters do we have?
func(x=9,z=90,y=3) Ans
Just 1
def fun(a=1,y=2,z=3): Data type: tuple
ag is a tuple
How many arguments I should in the
actual parameter to call the above
function?
Ans

Minimum =0
Maximum =3

Can i give more than 3?


Ans
No

How formal parameters you have and data


type?
Ans
3, of any type
def func1(*ag):
for L in ag:
for i

0 1 2 3
12 [1,2,3] “hello” 45.6
Cannot change change Cannot change Cannot change
ar[0]+=22
Number, string, float Changes are not possible

List the you can change

Change made in formal parameter which are List or Dictionary, then the changes will
reflected back in the actual parameter
23 | P a g e
Changes made in formal parameter which are integer, float, string or tuple then
changes will not be reflected in the actual parameter

Nested function
Function defined within a function
def f(): #outer function
print(“in f”)
def p(): #inner function
print(“in p”)
p() → call p function
Purpose:
To write a definition of a function inside another function

Example
1 def display():
2 def name():
3 print(“Niti Arora”)
4 name()
5 print(“I am a Python programmer”)
6 display()
7. print(“ok”)
Output
Niti Arora
I am Python Programmer
ok
6-->1-->4→ 2→ 3→ 5→ 7

Rewrite
1 def name():
2 print(“Niti Arora”)
3 def display():
4 name()
5 print(“I am a Python programmer”)
24 | P a g e
6 display()
7. print(“ok”)
Execution
6→ 3→ 4→ 1→ 2→ 5→ 7
Output WILL BE SAME
Niti Arora
I am a Python programmer
Ok

Format 3: No parameter and return


- You can give blank return
- Return means terminate the called function and go back to the calling function

Write a function in Python to accept 10 numbers in a function and display their sum, function
must return back it user inputs 0
def func():
sum=0
for i in range(10):
x=int(input("Enter the number or 0 to stop:"))
if x==0:
return
sum+=x
print("Sum=",sum)

func()

25 | P a g e
def func():
sum=0 def func():
for i in range(10): sum=0
x=int(input("Enter the for i in range(10):
number or 0 to stop:")) x=int(input("Enter the
if x==0: number or 0 to stop:"))
return if x==0:
sum+=x break
print("Sum=",sum) sum+=x
print("Sum=",sum)
func()
func()
It will not print sum It will print sum
Terminates the function Terminates the loop
Remember: return in a called function terminated the called functions and takes the
control back to calling function, only return is possible
def fact(n):
if n==0:
return
else:
F=1
for a in range(1,n+1):
F*=a
return F
here control will return to calling function without a value when n is 0 else it will
return factorial of n
What do you understand by else statement of a loop, when it will be executed?
Ans
Else statement loop when loop is executed completely
If there is a break statement then the else will be executed when the loop is not
terminated by the break statement. Else statements will be executed when the break
statement is not executed.

def func():
sum=0
for i in range(10):
x=int(input("Enter the number or 0 to stop:"))
if x==0:
break
26 | P a g e
sum+=x
else:
print("Sum=",sum)

func()
Functionally they are same
def func(): def func():
sum=0 sum=0
for i in range(10): for i in range(10):
x=int(input("Enter the number x=int(input("Enter the number
or 0 to stop:"))
or 0 to stop:"))
if x==0:
if x==0:
break
return
#still in the function out of
#goes back to main program out of
loop
function sum+=x
sum+=x else:
print("Sum=",sum) print("Sum=",sum)

func() func()

Returning data
To return data return variable/ value → value of the variable or value will be
returned in calling function
def func():
sum=0
for i in range(10):
x=int(input("Enter the number or 0 to stop:"))
sum+=x
return sum
func()

27 | P a g e
Value of sum will come back to call statement
How can the Call statement receive this value?????
Methods of received value in call statement, how to call a
function which returns some value:-
1. Receive value(s) in a variable(s)
S=func()
The value returned by the function func() will be
stored in the variable S
2. Received value can be displayed on the screen -
print(functionname()) or functionname() value will be
printed on the screen
print(func())
Or
func()

3. Call in any other statement or expression


a=[Link](func())
● First execute func()
● Value is substituted
● [Link]() with the value

How many times func() will be called?


Ans 3times

28 | P a g e
a=func()*[Link](func())+[Link](func(),3)

2 3

Are the following call statements the same or not? justify


your answer
(i) a=func()*[Link](func())+[Link](func(),3)
(ii) x=func()
a=x*[Link](x)+[Link](x,3)
Ans
(i) func() will called 3 times
(ii) func() will called once, value will be substituted in
the equation

4. Call in if or loop
if func()==10:
print(“sum is 10”)
else:
print(“sum is not 10”)

User defined function like built-in function


- Takes parameter(s)
- Return value

29 | P a g e
def Sum(x,y):
return x+y Call sum() place
answer and return
def Avg(x,y): after calculation
return Sum(x,y)/2

print(Avg(4,6))

Call Avg()
function

def func2(a):
return a**3
Like [Link]()
def func2(a,b):
return a**b

Remember:- A function can returns multiple values. The return values should be a
comma separated list of values. The multiple return values are returned as a tuple.
We can unpack the received value by specifying the same number of variables on
the left side of the function call.

Example 1: Example 2:
def add10(x,y,z): def add10(x,y,z):
return x+10, y+10, z+10 return x+10, y+10, z+10
x, y, z=10, 20, 30 x, y, z=10, 20, 30
result=add10(x,y,z) a,b,c=add10(x,y,z) #unpack
print(result) print(a,b,c)

Output Output:
(20, 30, 40) 20 30 40

30 | P a g e
SCOPE OF VARIABLES:
The part of the program where a variable is accessible can be defined as the scope of that variable.
There are two types of scope for variables:
1. Local Scope: A variable declared in a function-body is said to have local scope. It cannot be accessed
outside the function.
2. Global Scope: A variable declared in top level segment (main) of a program is said to have a global
scope.
Example:
def Sum (x, y) : # x,y,z local
z=x+y
return z
a=5 # a,b,s global
b=7
s = Sum (a, b)
print(s)
Use of variable in Python program
A variable declared in the main part of the program is a global variable
The variable can be used in any function
If you change the value of a global variable and it is mutable then the changes will be
reflected in then main program else it will a local copy of the variable called local variable

x=1
def f():
x=2 # local variable assign new memory and new value
print("x in f()=",x,"memory after changing=",id(x))
print("x in main program",x,"memory of x",id(x))
f()
print("x after calling f()=",x,"memory of x=",id(x))
Global variable is a mutable data type then changes in the function will be reflected in the
main program but if it is an immutable data type then Python will create a local copy of the
same variable and this local copy will be released when function gets over.
Any variable declared in function is local to that function, can be accessed ONLY in that
function

Python by default function are public or global


When Python creates a local variable?
Ans
● Any variable declared in a function is a local variable
● Any immutable global variable when assigned a new value in function

31 | P a g e
● A variable in the header of the function is a local variable
Use of global keyword
If a variable is declared in function using the keyword global then that variable is accessible
to the whole program.
Remember: ONLY after calling the function

x=1
def f():
global x
x=12
print(x)
A variable must be declared as global only when we want to change the value of an
immutable variable.

Variable main program → global variable, all the functions in the program can use these
variables
If called function try to change global variable and the variable is mutable change will be
reflected in the main program
If called function try to change global variable and the variable is immutable change will not
be reflected in the main program as the called function is OWN copy of the variable with
same (local copy) is known local variable.
If called function try to change the value of local variable and want to share with the main
program declare using keyword global
Lvalue or rvalue of a variable?
a=10 lvalue 2034566
10
id(a) - 2034566 b=10
print(a) 10 a
b
rvalue

2034568 Lvalue of both


a and b are
a=12 12 same AS THE
a
RVALUE is
id(a) - 2034568 SAME
print(a) 12
In mutuable data type
Python suppress the lvalue lvalue and rvalue both
changes

32 | P a g e
Python will not lvalue(memory) for the same rvalue( data).
If you have created global variable and If a variable is declared in the called
want to change value in the function and function and want to use in the
new value reflect in the main program then main program, use global to declare
use word global int the called function to the variable
declare the variable
a=10 def f():
def f(): global a
global a a=30
a=30
f()
f() print(a)
print(a)

New memory(lvalue) and suppress the


previous value

def Fun():
global x 5
x
x=30 #line 2
#local variable declared as global 7
variable
print(id(x))

x=5 #line1
print(id(x)) #lvalue of global
variable
Fun() Suppress the
print(x,id(x))#lvalue will the lvalue earlier
address assigned in function in line 1 takes
the lvalue in
Q Write the output on execution of the following Python code : line 2
def ALTER(Y=25):
global X
33 | P a g e
Y += X
X += Y
print(X,Y,sep="#")
X=5; Y=15
ALTER(Y)
ALTER()
print(X,Y,sep="@")

Dry run
X Y Local variable Alter Y
25 15 20 released

2nd call
X Y Local variable Alter Y gets default value
75 15 50 released

Output
Ist call
25#20
75#50
75@15

Use of variable in nested function


a=10
def f():
def f1():
print(a)
print(a)
f1()
f()

def f():
a=10 # the variable cannot be used outside f
def f1():
print(a)
f1()
print(a)
f()

a=10
34 | P a g e
def f():
global a # suppress a=10
a=20
def f1():
a=30 # local variable
print(a) #30
f1()
print(a) #20
f()
print(a) #20

a=10
def f():
a=20
def f1():
global a #suppress a=10 and a=20
a=30
print(a) #30
print(a) #20
f1()
print(a) #20
f()
print(a) #30

a=10
def f():
global a
a=20
def f1():
global a
a=30
print(a)
print(a) #20
f1()
print(a) #30
f()
print(a) #30
#20 if you are not calling f1()

Nonlocal - not local to this function will be applicable to outer function

35 | P a g e
Global in inner function ONLY Global in outer function and inner
function
a=10 a=10
def f(): def f():
a=20 #local variable global a
def f1(): #a=10 suppressed
global a a=20
a=30
def f1():
print(a) #30
global a
print(a) #20
f1() #a=20 suppressed
print(a) #20 a=30
# a is local variable of f print(a)
f() f1()
print(a) # 30 print(a) #30
f()
print(a) #30

By a creating nonlocal variables changes will be reflected in outer function but not in the
main program
a=10
def f():
a=20
def f1():
nonlocal a
a=30
#change will be for inner function and outer function
print(a) #30
print(a) #20
f1()
print(a) #30
f()
print(a) #10 no change in the global variable

36 | P a g e
Multiple Choice Questions
1 Which of the following is a valid function name?
a) Start_game( ) b) start game ( ) c) start-game( ) d) All of the above
2 If the return statement is not used in the function, then which type of value will be
returned by the function?
a) int b) str c) float d) None
3 What is the minimum and maximum value of c in the following code snippet?
import random
a=[Link](3,5)
b = [Link](2,3)
c=a+b
print(c)
a) 3, 5 b) 5, 8 c) 2, 3 d) 3, 3
4 pow ( ) function belongs to which library?
a) math b) string c) random d) maths
5 What is the data type of the object below?
L = (1, 23, ‘hello’,1)
a) list b) dictionary c) array d) tuple

6 What is returned by int ([Link](3, 2))?


a) 6 b) 9 c) error, third argument required d) error, too many arguments
7 Which of the following is not a type conversion function?
a) int( ) b) str ( ) c) input ( ) d) float ( )
8 Identify the module to which the following function load ( ) belong to?
a) math b) random c) pickle d) sys
9 How many argument(s) a function can receive?
a) Only one b) 0 or many c) Only more than one d) At least one
10 Give the output
def fun ( ):
global a
a=10
print(a)
a=5
fun ( )
print(a)
a) 10 b) 5 c) 5 d) 10
10 10 5 5
11 Value returning functions should be generally called from inside of an expression
a) True b) False
12 The variable declared inside the function is called a variable
a) global b) local c) external d) none of the above
13 These are predefined functions that are always available for use. For using them we don’t need
to import any module
a) built in function b) pre-defined function
c) user defined function d) none of the above

37 | P a g e
14 The of a variable is the area of the program where it may be referenced
a) external b) global c) scope d) local
15 If you want to communicate between functions i.e. calling and called statement, then you
should use
a) values b) return c) arguments d) none of the above
16 Find the flow of execution of the following code:
1. def calculate (a, b):
2. res=a**b
3. return res
4.
5. def study(a):
6. ans=calculate(a,b)
7. return ans
8.
9. n=2
10. a=study(n)
11. print(a)
a) 1 > 5 > 9 > 10 >5>6 >1> 2 > 3 >6 7 > 10>11 b) 5 > 9 > 10 > 6 > 2 > 3 > 7 > 11
c) 9 > 10 > 5 > 1 > 6 > 2 > 3 > 7 > 11 d) None of the above
17 A can be skipped in the function call statements
a) named parameter b) default parameter
c) keyword parameters d) all of the above
18 Write the output of the following:
a= (10, 12, 13, 12, 13, 14, 15)
print(max(a) + min(a) + [Link](2))
a) 13. b) 25 c) 26 d) Error
19 What is wrong with the following function definition?
def greet (name="Guest", age):
print (name, “is”, age, “years old”))
a). The syntax of print statement is wrong
b). Default parameter must follow required parameter
c). Function name cannot be greet
d). Nothing is wrong
20 Which of the following function definitions is INVALID?
a). def func(a, b=2, c=3): pass. b). def func(a=1, b, c=2): pass
c). def func(a, b, c=5): pass. d). def func(a=1, b=2, c=3): pass
ANSWERS
1 A 2 D 3 B 4 A 5 D 6 B

7 C 8 C 9 B 10 A 11 A 12 B

13 A 14 C 15 C 16 A 17 B 18 B

19 B 20 B

ASSERTION AND REASONING QUESTIONS


38 | P a g e
(a) Both A and R are true and R is the correct explanation for A
(b) Both A and R are true and R is not the correct explanation for A
(c) A is True but R is False
(d) A is false but R is True
1 Assertion(A): If the arguments in a function call match the number and order of arguments as
defined in the function definition, such arguments are called the positional arguments.
Reasoning(R): During a function call, the argument list first contains default arguments
followed by positional arguments.
2 Assertion(A): The random module is a built-in module to generate the pseudo-random values.
Reason(R): The randrange( ) function is used to generate a random number between the
specified range in its parameter.
3 Assertion (A): Global variable is declared outside the all the functions.
Reasoning (R): It is accessible through out all the functions.
4 Assertion (A): Built-in function is predefined in the language that are used directly.
Reason (R): print ( ) and input ( ) are built-in functions
5 Assertion (A): - In Python, statement return [expression] exits a function.
Reasoning (R): - Return statement passes back an expression to the caller.
A return statement with no arguments is the same as return None.

ANSWERS
1 (c) A is True but R is False
2 (b) Both A and R are true and R is not the correct explanation for A
3 (a) Both A and R are true and R is the correct explanation for A
4 (a) Both A and R are true and R is the correct explanation for A
5 (a) Both A and R are true and R is the correct explanation for A
Short Answer Questions/Long Answer Questions
1 Rewrite the following Python program after removing all the syntactical errors (if any),
underlining each correction:
def checkval
x = input ("Enter a number")
if x % 2 =0:
print (x, "is even")
elseif x<0:
print (x, "should be positive")
else:
print (x, "is odd")
2 Mani Ayyar, a python programmer, is working on a project which requires him to define a
function with name CalculateInterest( ).
He defines it as:
def CalculateInterest (Principal, Rate=.06, Time): # Code
But this code is not working; Can you help Mani Ayyar to identify the error in the above
function and with the solution?

39 | P a g e
3 Predict the possible output(s) of the following code. Also specify the maximum and minimum
value that can be assigned to the variable R when K is assigned value as 2.
import random
Signal=[‘stop’, ’wait’, ’go’]
for K in range (2,0, -1):
R=[Link](K)
print (Signal[R], end=” #”)
a. Stop#wait#go# b. wait#stop# c. go#wait# [Link]#stop#
4 Predict the output of the following code fragment
def display (x=2, y=3):
x=x+y
y+=2
print(x,y)
display ( )
display (5,1)
display (9)
a) 5 5 b)12 5 c) 5 6 d) 5 5
6 3 6 3 12 5 7 7
12 5 55 6 3 6 6
5 Predict the output of the following code snippet:
def Execute(M):
if M%3==0:
return M*3
else:
return M+10;
def Output(B=2):
for T in range (0, B):
print (Execute(T),"* ", end="")
print ( )
Output (4)
Output ( )
Output (3)
6. Find the output of the following program:
def ChangeIt(Text,C):
T=""
for K in range(len(Text)):
if Text[K]>='F' and Text[K]<='L':
T=T+Text[K]. lower ( );
elif Text[K]=='E' or Text[K]=='e':
T=T+C;
elif K%2==0:
T=T+Text[K]. upper ( )
else:
T=T+T[K-1]
print(T)
OldText="pOwERALone"
ChangeIt(OldText,"%")

40 | P a g e
7 What possible outputs are expected to be displayed on screen at the time of execution of the
program from the following code? Also specify the maximum value that can be assigned to each
of the variables L and U.
import random
Arr= [10,30,40,50,70,90,100]
L=[Link](1,3)
U=[Link](3,6)
for i in range (L, U+1):
print (Arr[i],"@”, end="")
i) 40 @50 @ ii) 10 @50 @70 @90 @
iii) 40 @50 @70 @90 @ iv) 40 @100 @
8 What will be the output of the following code
total=0
def add(a,b):
global total
total=a+b
print(total)
add (6,6)
print(total)
a) 12 b) 12 c) 0 d) None of these
9 What possible output(s) are expected to be displayed on screen at the time of
execution of the following code? Also specify the maximum and minimum value
that can be assigned to variable X.
import random
L= [10,7,21]
X=[Link](1,2)
for i in range(X):
Y=[Link](1, X)
print(L[Y],"$”, end=" ")

(i)10 $ 7 $ (ii) 21 $ 7 $ (iii) 21 $ 10 $ (iv) 7 $


10 Vivek has written a code to input a number and check whether it is even or odd
number. His code is having errors. Rewrite the correct code and underline the
corrections made.
Def checkNumber(N):
status = N%2
return
#main-code
num=int (input (“Enter a number to check :))
k=checkNumber(num)
if k = 0:
print (“This is EVEN number”)
else:
print (“This is ODD number”)

41 | P a g e
11 Find and write the output of the following Python code:
def changer(p,q=10):
p=p/q
q=p%q
print(p,"#",q)
return p
a=200
b=20
a=changer(a,b)
print(a,"$",b)
a=changer(a)
print(a,"$",b)
12 Write a function INDEX_LIST(L), where L is the list of elements passed as argument to the
function. The function returns another list named ‘indexList’ that stores the indices of all Non-
Zero Elements of L.
For example: If L contains [12,4,0,11,0,56] The indexList will have – [0,1,3,5]
ANSWERS
1 def checkval ( ):
x = int (input ("Enter a number"))
if x % 2 == 0:
print (x, "is even")
elif x<0:
print (x, "should be positive")
else:
print (x, "is odd")
2 Non-default argument must appear before default argument
Correct definition: def CalculateInterest(Principal, Time ,Rate=.06,):
3 b) wait#stop#
Max value of R=1, Min value of R=0
4 Ans. a)
5 Ans.
0 *11 *12 *9 *
0 *11 *
0 *11 *12 *
6 PPW%RRllN%
7 Ans. Options i and iii
i)40 @50 @
iii) 40 @50 @70 @90 @
Maximum value of L and U : L=2 ,U=5
8 Ans : a)
9 Ans. iv) 7 $
Maximum value of x is 2
Minimum value of x is 1

42 | P a g e
10 def checkNumber(N): # Def should be def
status = N%2
return status
#main-code
num=int( input(“ Enter a number to check : “)) # Message not enclosed within quotation mark
k=checkNumber(num)
if k == 0:
print(“This is EVEN number”)
else:
print(“This is ODD number”)
11 Ans.
10.0 # 10.0
10.0 $ 20
1.0 # 1.0
1.0 $ 20
12 def INDEX_LIST(L):
indexList= []
for i in range(len(L):
if L[i]! =0:
[Link](i)
return indexList

43 | P a g e

You might also like