0% found this document useful (0 votes)
39 views12 pages

CBQs On Function

The document contains a series of questions and answers related to Python functions, covering topics such as variable scope, function outputs, and error handling. Each question presents a code snippet or a scenario, followed by multiple-choice answers or requests for code corrections. The answer key provides the correct answers for each question, indicating the expected outputs or corrections needed.

Uploaded by

sushrudhdogra26
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views12 pages

CBQs On Function

The document contains a series of questions and answers related to Python functions, covering topics such as variable scope, function outputs, and error handling. Each question presents a code snippet or a scenario, followed by multiple-choice answers or requests for code corrections. The answer key provides the correct answers for each question, indicating the expected outputs or corrections needed.

Uploaded by

sushrudhdogra26
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

CBQs on Function

Q1 Consider the code given below: Which of the following statements should be given in the blank for
Statement1, if the output for statement2 is 110?
b=100
def test(a):
________ # Statement 1
b=b+a
print(a,b)
test(10)
print(b) # Statement 2
a) global a b) global b=100 c) global b d) global a=100
Q2 What will be the output?
def increment(x):
x+=1
return x
value=5
print(increment(value))
a) 5 b) 6 c) 4 d) This code will raise an error.
Q3 What will be the output of the following code
a=10
def call():
global a
b=20
a=a+b
print(a)
call()
a) 10 b) 30 c) error d) 20
Q4 What will be the output of the Python code?
def testify(a,b):
return (a-b)
sum=testify(22,55)
sum=sum+30
print(sum)
a) 33 b) -33 c) 3 d) -3
Q5 What will be the output of the following code?
def a(b=11,c=21):
b+=13
c -=13
return b+c
print (a(25), a(35))
a) 15 18 b) 46 56 c) 25 35 d) 13 12
Q6 num =100
def showval(X):
global num
num = 85
if(X%2==0):
num += X
else:
num -= X
print(num,end="#")
showval(33)
print(num)

a) 100#52 b) 85#52 c) 85#33 d) 185#52


Q7 Look at the function definition and the function call and determine the correct output
def test(a):
if(a>10):
a += 10
if(a>20):
a += 20
if(a>30):
a +=30
print(a)
test(11)
Q8 def modify_list(lst):
lst.append(6)
lst[0] = 100
numbers=[1, 2, 3, 4, 5]
modify_list(numbers)
print(numbers)
a) (1, 2, 3, 4, 5, 6] b) [100, 2, 3, 4, 5, 6] c) [100, 2, 3, 4, 5] d) (1, 2, 3, 4, 5]
Q9 Predict output:
def modify_list(lst):
lst=[1, 2, 3, 4]
numbers=[5, 6, 7]
modify_list(numbers)
print(numbers)
Q10 What will be the output of the following Python code?
def add(num1, num2):
sum=num1 + num2
sum=add(20,30)
print(sum)
Q11 Find and write the output of following python code
def Alter(M,N=45):
M=M+N
N=M-N
print(M,"@")
return M
A=Alter(20,30)
print(A,"#")
B=Alter(30)
print(B,"#")
Q12 Predict output:
global_var =10
def func1():
print("Inside func1:", global_var)
def func2():
global global_var
global_var=20
func1()
print("Outside any function:",global_var)
func2()
print("After func2:",global_var)
Q13 Predict output:
def Changer(P,Q=10) :
P=P/Q
Q=P%Q
return P
A=200
B=20
A=Changer(A,B)
print (A,B,sep='$')
Q14 Rewrite the following code after removing the syntactical errors (if any). Underline each correction.
def chksum:
x=int( input ("Enter a number"))
if (x%2=0) :
for i range (2* x) :
print i
else:
print "#"
Q15 What will be the output of the following code?
def my_func(var1=100, var2=200):
var1+=10
var2=var2-10
return var1+var2
print(my_func(50), my_func())
Q16 What will be the output of the following code?
value=50
def display(N):
global value
value=25
if N%7==0:
value =value+N
else:
value= value-N
print(value,end='#')
display(20)
print(value)
Q17 What will be the output of the following code?
def short_sub(lst,n):
for i in range (0,n) :
if len(lst)>4:
lst[i]=lst[1]+lst[i]
else:
lst[i]=lst[i]
subject=['CS','HINDI','PHYSICS','CHEMISTRY','MATHS']
short_sub(subject, 5)
print(subject)
Q18 What is the output of the following code snippet?
a=30
def call(x):
global a
if a%2==0:
x+=a
else:
x-=a
return x
x=20
print(call(35),end="#")
print (call(40),end= "@")
19 What will be the output of the following code?
def Changeval (M,N) :
for i in range(N):
if M[i]%5==0 :
M[i]//=5
if M[i]%3==0 :
M[i]//=3
L=[25,8,75,12]
Changeval(L,4)
for I in L:
print(I,end='#')
20 What will be the output of the following code?
x=3
def myfunc():
global x
x+=2
print(x,end='')
print(x,end=' ')
myfunc()
print(x,end=' ')
21 def makenew(mystr):
newstr = ""
count = 0
for i in mystr:
if count%2 != 0:
newstr = newstr + str(count)
else:
if i.islower():
newstr = newstr + i.upper()
else:
newstr = newstr + i
count += 1
newstr = newstr + mystr[:1]
print("The new string is:", newstr)
makenew("sTUdeNT")
22 Write a user defined function findname(name) where name is an argument in Python to delete
phone number from a dictionary phonebook on the basis of the name, where name is the key.
23 def Call(P = 40, Q = 20):
P=P+Q
Q=P-Q
print(P, '@', Q)
return P
R = 200
S = 100
R = Call(R, S)
print(R, '@', S)
S = Call(S)
print(R, '@', S)
24 Write a function to calculate volume of a box with appropriate default values for its parameters.
Your function should have the following input parameters :
(a) length of box ; (b) width of box ; (c) height of box.
Test it by writing complete program to invoke it.
25 Write a program to have following functions :
(i) a function that takes a number as argument and calculates cube for it. The function does not
return a value. If there is no value passed to the function in function call, the function should
calculate cube of 2.
(ii) a function that takes two char arguments and returns True if both the arguments are equal
otherwise False.
Test both these functions by giving appropriate function call statements.
26 Write a function that receives two numbers and generates a random number from that range. Using
this function, the main program should be able to print three numbers randomly.
27 Write a function that receives two string arguments and checks whether they are same-length
strings (returns True in this case otherwise False).
28 Write a function namely nthRoot( ) that receives two parameters x and n and returns nth root of x
i.e., x^(1/n).
The default value of n is 2.
29 Write a function that takes a number n and then returns a randomly generated number having
exactly n digits (not starting with zero) e.g., if n is 2 then function can randomly return a number 10-
99 but 07, 02 etc. are not valid two digit numbers.
30 Write a function that takes two numbers and returns the number that has minimum one's digit.
[For example, if numbers passed are 491 and 278, then the function will return 491 because it has
got minimum one's digit out of two given numbers (491's 1 is < 278's 8)].
31 Write a program that generates a series using a function which takes first and last values of the
series and then generates four terms that are equidistant e.g., if two numbers passed are 1 and 7
then function returns 1 3 5 7.
32 Write Python program to find the sum of natural numbers up to n using function.
33 Write code to compute the factorial of an integer.
34 Write program to find the H.C.F of two input number.
35 Write Python program to find the product of natural numbers up to n using function.
36 Write a function countNow(PLACES) in Python, that takes the dictionary, PLACES as an argument
and displays the names (in uppercase)of the places whose names are longer than 5 characters.
For example, Consider the following dictionary
PLACES={1:"Delhi",2:"London",3:"Paris",4:"NewYork",5:"Doha"}
The output should be:
LONDON
NEW YORK
37 Write a function, lenWords(STRING), that takes a string as an argument and returns a tuple
containing length of each word of a string.
For example, if the string is "Come let us have some fun", thetuple will have (4, 3, 2, 4, 4, 3)
38 Write a function in Python to read a string and display the number of times word ‘You’ occurs in the
string.
39 Write a function, vowelCount() in Python that counts and displays the number of vowels in the text
file named Poem.txt
40 Write a method in Python to find and display the prime number between 2 to N.Pass N as argument
to the method.
41 Write a python program to reverse a string using function string_reverse.
42 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)
B=Changer(B)
print (A,"$",B)
A=Changer(A)
print (A,"$",B)
43 Write definition of a method/functi0n AddOddEven(VALUES) to display sum of odd and even values
separately from the list VALUES.
For example:
If the VALUES contain [15, 26, 37, 10, 22, 13]
The function should display
Even Sum: 58
Odd Sum: 65
44 Write a function LShift(Art,n) in Python, which accepts a list Art of numbers and n is a numeric value
by which all elements of the list are shifted to left.
Sample Input Data of the list Arr= [ 10,20,30,40,12,11], n=2
Output
Агг = [30,40,12,11,10,20]
45 Write a python method/function Swapper (Numbers) to swap the first half of the content of a list
Numbers with second half of the content of list Numbers and display the swapped values.
Note: Assuming that the list has even number of values in it.
For example:
If the list Numbers contains [35,67,89,23,12,45]
After swapping the list content should be displayed as [23,12,45,35,67,89]
46 What will be the output of the following code?
c = 10
def add():
global c
c=c+2
print(c,end='#')
add()
c=15
print(c,end='%')
(A) 12%15# (B) 15#12% (C) 12#15% (D) 12%15#
47 Write definition of a method/function HowMany (ID, Val) to count and display number of times the
value of Val is present in the list ID.
For example:
If the ID contains [115,122,137,110,122,113] and Val contains 122
The function should display 122 found 2 Times

48 Write definition of a method Even Sum(NUMBERS) to add those values in the list of NUMBERS,
which are odd.
49 Write the definition of a method ZeroEnding (SCORES) to add all those values in the list of SCORES,
which are ending with zero (0) and display the sum.
For example:
If the SCORES contain [200, 456, 300, 100, 234, 678]
The sum should be displayed as 600
50 Find and write the output of the following Python code:
def Display(str):
m=""
for i in range(0,len(str)):
if(str[i].isupper()):
m=m+str[i].lower()
elif str[i].islower():
m=m+str[i].upper()
else:
if i%2==0 :
m=m+str[i-1]
else:
m=m+”#”
print(m)
Display('[email protected]')

Answer key on Function


Q1 C
Q2 B
Q3 B
Q4 D
Q5 B
Q6 A
Q7 71
Q8 B
Q9 [5, 6, 7]
Q10 None
Q11 50 @
50 #
75 @
75 #
12 Inside func1: 10
Outside any function: 10
After func2: 20
13 10.0$20
14 def chksum():
x=int(input("Enter a number"))
if(x%2==0):
for i in range(2* x) :
print(i)
else:
print("#")
15 250 300
16 50#5
17 ['HINDICS', 'HINDIHINDI', 'HINDIHINDIPHYSICS', 'HINDIHINDICHEMISTRY', 'HINDIHINDIMATHS']
18 None#None@
19 5#8#5#4#
20 3 55
21 The new string is: S1U3E5Ts
22 def findname(name):
if name in phonebook:
del phonebook[name]
else:
print("Name not found")
print("Phonebook Information")
print("Name",'\t', "Phone number")
for i in phonebook.keys():
print(i,'\t', phonebook[i])
23 300 @ 200
300 @ 100
120 @ 100
300 @ 120
24 def calculate_volume(length = 5, width = 3, height = 2):
return length * width * height

default_volume = calculate_volume()
print("Volume of the box with default values:", default_volume)

v = calculate_volume(10, 7, 15)
print("Volume of the box with positional arguments:", v)

a = calculate_volume(length = 23, height = 6)


print("Volume of the box with default and keyword arguments:", a)

b = calculate_volume(width = 19)
print("Volume of the box with default and keyword args:", b)

25 # Function to calculate cube of a number


def calculate_cube(number = 2):
cube = number ** 3
print("Cube of", number, "is", cube)

# Function to check if two characters are equal


def check_equal_chars(char1, char2):
return char1 == char2
calculate_cube(3)
calculate_cube()
char1 = 'a'
char2 = 'b'
print("Characters are equal:", check_equal_chars(char1, char1))
print("Characters are different:", check_equal_chars(char1, char2))

26 import random
def generate_random_number(num1, num2):
low = min(num1, num2)
high = max(num1, num2)
return random.randint(low, high)
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
for i in range(3):
random_num = generate_random_number(num1, num2)
print("Random number between", num1, "and", num2, ":", random_num)
27 def same_length_strings(str1, str2):
return len(str1) == len(str2)
s1 = "hello"
s2 = "world"
s3 = "python"
print(same_length_strings(s1, s2))
print(same_length_strings(s1, s3))
28 def nthRoot(x, n = 2):
return x ** (1/n)
x = int(input("Enter the value of x:"))
n = int(input("Enter the value of n:"))
result = nthRoot(x, n)
print("The", n, "th root of", x, "is:", result)
default_result = nthRoot(x)
print("The square root of", x, "is:", default_result)
29 import random
def generate_number(n):
lower_bound = 10 ** (n - 1)
upper_bound = (10 ** n) - 1
return random.randint(lower_bound, upper_bound)
n = int(input("Enter the value of n:"))
random_number = generate_number(n)
print("Random number:", random_number)
30 def min_ones_digit(num1, num2):
ones_digit_num1 = num1 % 10
ones_digit_num2 = num2 % 10
if ones_digit_num1 < ones_digit_num2:
return num1
else:
return num2
num1 = int(input("Enter first number:"))
num2 = int(input("Enter second number:"))
result = min_ones_digit(num1, num2)
print("Number with minimum one's digit:", result)
31 def generate_series(first, last):
step = (last - first) // 3
series = [first, first + step, first + 2 * step, last]
return series

first_value = int(input("Enter first value:"))


last_value = int(input("Enter last value:"))
result_series = generate_series(first_value, last_value)
print("Generated Series:", result_series)
32 def sum(n):
s=0
for i in range(1,n+1):
s+= i
return s
num = int(input(‘Enter a number:’))
if num < 0:
print("Enter a positive number")
else:
print("The sum is",sum(num))
33 def calc_factorial(x):
f=1
for i in range(1,x+1):
f*=i
return f
num = int(input(‘Enter a number:’))
print("The factorial of", num, "is", calc_factorial(num))
34 def computeHCF(x, y):
if x > y:
smaller = y
else:
smaller = x
for i in range(1, smaller+1):
if((x % i == 0) and (y % i == 0)):
hcf = i
return hcf
num1 = 54
num2 = 24
print("The H.C.F. of", num1,"and", num2,"is", computeHCF(num1, num2))
35 def product(n):
p=1
for i in range(1,n):
p *= i
return p
num = int(input(‘Enter a number:’))
if num < 0:
print("Enter a positive number")
else:
print("The sum is",recur_sum(num))
36 PLACES={1:"Delhi",2:"London",3:"Paris",4:"New York",5:"Dubai"]
def countNow (PLACES):
for place in PLACES.values():
if len(place)>5:
print(place.upper())
count Now (PLACES)
37 def lenWords (STRING):
T=()
L=STRING.split()
for word in L:
length=len (word)
T=T+(length,)
return T
38 def test():
data = input(‘Enter a string:’)
wl = data.split()
c=0
for w in wl:
if w == "You":
c+=1
print(c)
39 def vowelCount():
data = input(‘Enter a string:’)
cnt=0
for ch in data:
if ch in "aeiouAEIOU":
cnt=cnt+1
print(cnt)
40 def prime(N):
for a in range(2,N):
for i in range(2,a):
if a%i==0:
break
else:
print(a)
41 def string_reverse(str1):
rstr=””
I ndex=len(str1)
while index>0:
rstr1+=str1[index-1]
index=index-1
return rstr1
print(string_reverse(‘1234abcd’))
42 10.0#10.0
10.0$20
2.0#2.0
1.0#1.0
1.0$2.0
43 def AddOddEven (VALUES):
oddSum=0
evenSum=0
for i in range(len(VALUES)):
if VALUES[i]%2==0:
evenSum=evenSum+VALUES[i]
else:
oddSum=oddSum+VALUES[i]
print("Even Sum:", evenSum)
print("Odd Sum:", oddSum)
values=[15, 26, 37, 10, 22, 13]
AddOddEven(values)
44 def LShift(Arr,n):
L=len(Arr)
for x in range(0,n):
y=Arr[x]
for i in range(0,L-1):
Arr[i]=Arr[i+1]
Arr[L-1]=y
print(Arr)
45 def Swapper (Numbers):
mid=int(len(Numbers)/2)
for i in range(0,mid):
T=Numbers[i]
Numbers[i]=Numbers[mid+i]
Numbers[mid + i]=T
print (Numbers)
46 12#15%
47 def HowMany(ID,Val):
count = 0
for i in ID:
if i == Val:
count = count + 1
print(count)
l = [115,122,137,110,122,113]
va = 122
HowMany(l,va)
48 def EvenSum(NUMBERS):
n=len(NUMBERS)
S=0
for i in range(n):
if (i%2==1):
S=S+ NUMBERS[i]
print(S)
49 def ZeroEnding(SCORES):
SZero = 0
for i in SCORES:
if i % 10 == 0:
SZero += i
print ("sum of numbers ending with zero: ", SZero)
50 fUN#pYTHONn#

You might also like