Understanding Python Functions Basics
Understanding Python Functions Basics
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
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)
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)
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
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
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:
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
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
a=10
display(a) display(10)
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
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)
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)
# 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.
● 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.
14 | P a g e
Keyword-Only Argument Positional-Only Argument
Syntax : -
Syntax :-
FunctionName(paramName=value,...)
FunctionName(value1,value2,value3,....)
def display(name,age,subject):
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
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
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
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
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
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()
28 | P a g e
a=func()*[Link](func())+[Link](func(),3)
2 3
4. Call in if or loop
if func()==10:
print(“sum is 10”)
else:
print(“sum is not 10”)
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
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
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)
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
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()
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
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
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=" ")
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