Functions Exercises 2
Functions Exercises 2
Functions Exercises 2
- Exercises Part 2
Trace the flow of execution for the following program:
1. def power(b,p):
2. r=b**p
3.return r 4.
5. def calcsquare(a):
6. a=power(a,2)
7.return a
8.
9. n=5
10.result=calcsquare(n)
11.print(result)
Flow of execution
1->5->9->10->5->6->1>2->3->6->7->10->11
What are the errors in following code?
Correct the code and predict output:
total=0
def sum(arg1,arg2)
total=arg1+arg2
return total
sum(10, 20)
print(“total:”,total)
Corrected Code
total=0
def sum(arg1,arg2):
total=arg1+arg2
return total
total=sum(10, 20)
print(“total:”,total)
Output
total: 30
Identify the errors in the following code.
Correct the code and predict output:
def tot(number)
sum=0
for c in range(1,number+1)
sum+=c
RETURN
su
m print(tot[3])
print(tot[6])
Corrected Code
def tot(number):
sum=0
for c in range(1,number+1):
sum+=c
return sum
print(tot(3))
print(tot(6))
Output
6
21
In the following code,
which variables are in the same scope?
def func1( ):
a=1
b=2
def func2( ):
c=3
d=4
e=5
Answer
def func1( ):
a=1 Local variable
def func2( ):
c=3 Local variable
(i) No output
(ii) 25
Write a function namely fun
that takes no parameters and always returns None.
def fun( ):
return
f=fun( )
print(f)
Output
None
Following code intends to add a given value
to global variable a.
What will the following code produce?
def increase(x):
a=a+x
return
a=20
b=5
increase(b)
print(a)
def increase(x):
global a
a=a+x
return
a=20
b=5
increase(b)
print(a)
Output
25
Write a Python program using function to print
the even numbers from a given list.
Sample List: [1,2,3,4,5,6,7,8,9]
Expected Result: [2,4,6,8]
def even(l):
l1=[ ]
for i in l:
if i%2==0:
l1.append(i)
return l1
print(even([1,2,3,4,5,6,7,8,9]))
Output
[2, 4, 6, 8]
Write a Python program using function to count the
number of uppercase and lowercase characters in a string
def upperlower(s1):
uc=lc=0
for i in s1:
if i.isupper( ):
uc=uc+1
elif i.islower( ):
lc=lc+1
return uc,lc
s=input("enter a string")
u, l=upperlower(s)
print("Number of uppercase characters", u)
print("Number of lowercase characters", l)