FUNCTIONS
- Exercises
What will the following code print?
def addEm(x,y,z):
print(x+y+z) #48
def prod(x,y,z):
return x* y*z
a=addEm(6,16,26)
b=prod(2,3,6)
print(a,b)
Output
48
None 36
Consider below given function headers.
Identify which of these will cause error and
why?
(i) def func(a=1,b):
(ii) def func(a=1,b,c=2):
(iii)def func(a,b,c=2):
(iv)def func(a=1,b=1,c=2,d):
Answer
Function Headers (i),(ii) and (iv) will cause error
because default arguments can assign default
values from right to left.
Only function header (iii) will not cause any error.
Predict the output of the following code fragment
def func(message, num=1):
print(message*num)
func(„Python‟)
func(„Easy‟,3)
Output
Python
EasyEasyEasy
What is the output of the following code?
a=1
def f():
a=10
print(a) #10
f()
print(a) #1
Output
10
1
What is the output of the following code?
num=1
def myfunc( ):
num=10
return num
print(num) #1
print(myfunc( )) #10
print(num) #1
Output
1
10
1
What is the output of the following code?
num=1
def myfunc( ):
global num
num=10
return num
print(num) #1
print(myfunc( )) #10
print(num) #10
Output
1
10
10
What is the output of the following code?
def power(x, y=3): #x=2, y=5
r=1
for i in range(y): #i=0 to 4
r=r*x #r=1*2=2
return r
print(power(5)) #5
print(power(2,5)) #2
Output
5
2
What is the output of the following code?
def func(x,y=100,z=1000):
print(„x=„,x,‟y=„,y,‟and z=„,z)
func(5,15,25)
func(35,z=55)
func(y=70,x=200)
Output
x= 5 y= 15 and z= 25
x= 35 y= 100 and z= 55
x= 200 y= 70 and z= 1000
What is the output of the following code?
def display(name,deptt,sal):
print(“Name”,name)
print(“Department”,deptt)
print(“Salary”,sal)
display(sal=10000,name=“Tavisha”,deptt=“IT”)
display(deptt=“HR”,name=“Dev”,sal=5000)
Output
Name Tavisha
Department IT
Salary10000
Name Dev
Department
HR Salary
5000
What is the output of the following code?
def increment(n): #n=[1,2,3]
n.append([4]) #n=[1,2,3,[4]]
return n
L=[1,2,3]
M=increment(L) #M=[1,2,3,[4]]
print(L,M)
Output
[1, 2, 3, [4]] [1, 2, 3, [4]]
What is the output of the following code?
def increment(n): #n=[23,35,47]
n.append([49]) #n=[23,35,47,[49]]
return n[0],n[1],n[2],n[3]
L=[23,35,47]
m1,m2,m3,m4=increment(L)#(23 ,35, 47, [49])
print(L) #L=[23,35,47,[49]]
print(m1,m2,m3,m4) #23 35 47 [49]
print(L[3]==m4) #[49]==[49] True
Output
[23, 35, 47, [49]]
23 35 47 [49]
True