MCQ (Revision Tour, Functions and File Handling) With Solution
MCQ (Revision Tour, Functions and File Handling) With Solution
MCQ (Revision Tour, Functions and File Handling) With Solution
4. The function divmod(a,b), where both ‘a’ and ‘b’ are integers is evaluated as:
a) (a%b, a//b) b) (a//b, a%b)
c) (a//b, a*b) c) (a/b, a%b)
Answer: b
EXPLANATION: The function divmod(a,b) is evaluated as a//b, a%b, if both ‘a’ and ‘b’ are integers.
4. Which of the following functions will not result in an error when no arguments are passed to it?
a) min()b) divmod() c) all() d) float()
Answer: d
EXPLANATION: The built-in functions min(), max(), divmod(), ord(), any(), all() etc throw an error when no arguments are passed
to them. However there are some built-in functions like float(), complex() etc which do not throw an error when no arguments are
passed to them. The output of float() is 0.0.
9.
In the second usage func(25, c=24), the variable a gets the value of 25 due to the position of the argument. Then, the parameter
c gets the value of 24 due to naming i.e. keyword arguments. The variable b gets the default value of 5.
In the third usage func(c=50, a=100), we use keyword arguments for all specified values. Notice that we are specifying the
value for parameter c before that for a even though a is defined before c in the function definition.
9. What is the output of below
program? def maximum(x, y):
if x > y:
return x
elif x == y:
return 'The numbers are equal'
else:
return y
print(maximum(2, 3))
a) 2 b) 3 c) The numbers are equal
d) None of the mentioned
Answer: b
EXPLANATION: The maximum function returns the maximum of the parameters, in this case the numbers supplied to the
function. It uses a simple if..else statement to find the greater value and then returns that value.
a) 9b) 3 c) 27 d) 30
Answer: c
EXPLANATION: A function is created to do a specific task. Often there is a result from such a task. The return keyword is used
to return values from a function. A function may or may not return a value. If a function does not have a return keyword, it will
send a none value.
8. If a function doesn’t have a return statement, which of the following does the function
return? a)int b)null c)None
d) An exception is thrown without the return statement
Answer: c
EXPLANATION: A function can exist without a return statement and returns None if the function doesn’t have a return statement.
9. What is the output of the following
code? def display(b, n):
while n > 0:
print(b,end="")
n=n-1
display('z',3)
a)zzz b)zz c)An exception is executed d)Infinite loop
Answer: a
EXPLANATION: The loop runs three times and ‘z’ is printed each time.
5. How many keyword arguments can be passed to a function in a single function call?
a) zero b) one c) zero or more d) one or more
Answer: c
EXPLANATION: zero keyword arguments may be passed if all the arguments have default values.
3. Which module in the python standard library parses options received from the command line?
a) getopt b) os c) getarg d) main
Answer: a
EXPLANATION: getopt parses options received from the command line.
9. Where are the arguments received from the command line stored?
a) sys.argv b) os.argv
c) argv d) none of the mentioned
Answer: a
EXPLANATION: Refer documentation.
hello
Answer: a
EXPLANATION: The code shown above will result in an error because ‘x’ is a global variable. Had it been a local variable, the
output would be: 16
hello
p,q,r,s = 1,2,3,4
f(5,10,15)
a) 1 2 3 4 b) 5 10 15 4
c) 10 20 30 40 d) 5 10 15 40
Answer: c
EXPLANATION: The above code shows a combination of local and global variables. The output of this code is: 10 20 30 40
13. Read the code shown below carefully and point out the global variables:
y, z = 1, 2
def f():
global x
x = y+z
a) x b) y and z
c) x, y and z d) Neither x, nor y, nor z
Answer: c
EXPLANATION: In the code shown above, x, y and z are global variables inside the function f. y and z are global because they
are not assigned in the function. x is a global variable because it is explicitly specified so in the code. Hence, x, y and z are
global variables.
3. On assigning a value to a variable inside a function, it automatically becomes a global variable. State whether true or false.
a) True b) False
Answer: b
EXPLANATION: On assigning a value to a variable inside a function, t automatically becomes a local variable. Hence the above
statement is false.
5. What happens if a local variable exists with the same name as the global variable you want to access?
a) Error b) The local variable is shadowed
c) Undefined behavior d) The global variable is shadowed
Answer: d
EXPLANATION: If a local variable exists with the same name as the local variable that you want to access, then the global
variable is shadowed. That is, preference is given to the local variable.
1. What is returned by
math.ceil(3.4)? a) 3 b) 4 c) 4.0
d) 3.0 Answer: b
EXPLANATION: The ceil function returns the smallest integer that is bigger than or equal to the number itself.
4. Is the output of the function abs() the same as that of the function math.fabs()?
a) sometimes b) always
c) never d) none of the mentioned
Answer: a
EXPLANATION: math.fabs() always returns a float and does not work with complex numbers whereas the return type of abs() is
determined by the type of value that is passed to it.
7. What is math.factorial(4.0)?
a) 24 b) 1 c) error d) none of the mentioned
Answer: a
EXPLANATION: The factorial of 4 is returned.
9. What is
math.floor(0o10)? a) 8 b) 10
c) 0 d) 9 Answer: a
EXPLANATION: 0o10 is 8 and floor(8) is 8.
Python MCQ of – Math Module – 2
1. To include the use of functions which are present in the random library, we must use the option:
a) import random b) random.h
c) import.random d) random.random
Answer: a
EXPLANATION: The command import random is used to import the random module, which enables us to use the functions
which are present in the random library.
2. The output of the following snippet of code is either 1 or 2. State whether this statement is true or
false. import random
random.randint(1,2)
a) True
b) False
Answer: a
EXPLANATION: The function random.randint(a,b) helps us to generate an integer between ‘a’ and ‘b’, including ‘a’ and ‘b’. In
this case, since there are no integers between 1 and 2 , the output will necessarily be either 1 or 2’.
3. What is the interval of the value generated by the function random.random(), assuming that the random module has already
been imported?
a) (0,1) b) (0,1] c) [0,1] d) [0,1)
Answer: d
EXPLANATION: The function random.random() generates a random value in the interval [0,1), that is, including zero but
excluding one.
6. The randrange function returns only an integer value. State whether true or false.
a) True
b) False
Answer: a
EXPLANATION: The function randrange returns only an integer value. Hence this statement is true.
7. Which of the following options is the possible outcome of the function shown
below? random.randrange(1,100,10)
a) 32 b) 67 c) 91 d) 80
Answer: c
EXPLANATION: The output of this function can be any value which is a multiple of 10, plus 1. Hence a value like 11, 21, 31,
41…91 can be the output. Also, the value should necessarily be between 1 and 100. The only option which satisfies this criteria
is 91.
Python MCQ of – Random Module – 2
1. The function random.randint(4) can return only one of the following values. Which?
a) b) 3.4 c) error d) 5
Answer: c
EXPLANATION: Error, the function takes two arguments.
EXPLANATION: The function getcwd() (get current working directory) returns a string that represents the present working
directory.
6. To read the entire remaining contents of the file as a string from a file object infile, we use
a) infile.read(2) b) infile.read()
c) infile.readline() d) infile.readlines()
Answer: b
EXPLANATION: read function is used to read all the lines in a file.
7. What is the
output? f = None
for i in range (5):
with open("data.txt", "w") as f:
if i > 2:
break
print(f.closed)
a) True b) False c) None d) Error
Answer: a
EXPLANATION: The WITH statement when used with open file guarantees that the file object is closed when the with block
exits.
8. To read the next line of the file from a file object infile, we use
a) infile.read(2) b) infile.read()
c) infile.readline() d) infile.readlines()
Answer: c
EXPLANATION: Execute in the shell to verify.
9. To read the remaining lines of the file from a file object infile, we use
a) infile.read(2) b) infile.read()
c) infile.readline() d) infile.readlines()
Answer: d
EXPLANATION: Execute in the shell to verify.
Answer: a
EXPLANATION: The tell() method tells you the current position within the file; in other words, the next read or write will occur
at that many bytes from the beginning of the file.
EXPLANATION: Sets the file’s current position at the offset. The method seek() sets the file’s current position at the offset.
Following is the syntax for seek() method:
fileObject.seek(offset[, whence])
Parameters
offset — This is the position of the read/write pointer within the file.
whence — This is optional and defaults to 0 which means absolute file positioning, other values are 1 which means seek
relative to the current position and 2 means seek relative to the file’s end.
10. Which of the following is modes of both writing and reading in binary format in file.?
a) wb+ b) w
c) wb d) w+
Answer: a
EXPLANATION: Here is the description below
“w” Opens a file for writing only. Overwrites the file if the file exists. If the file does not exist, creates a new file for writing.
“wb” Opens a file for writing only in binary format. Overwrites the file if the file exists. If the file does not exist, creates a new
file for writing.
“w+” Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a
new file for reading and writing.
“wb+” Opens a file for both writing and reading in binary format. Overwrites the existing file if the file exists. If the file does
not exist, creates a new file for reading and writing.
3. How do you get the name of a file from a file object (fp)?
a) fp.name b) fp.file(name)
c) self. name (fp) d) fp. name ()
Answer: a
EXPLANATION: name is an attribute of the file object.
9. How do you change the file position to an offset value from the start?
a) fp.seek(offset, 0) b) fp.seek(offset, 1)
c) fp.seek(offset, 2) d) none of the mentioned
Answer: a
EXPLANATION: 0 indicates that the offset is with respect to the start.
1 MARKS QUESTIONS
1. Which of the following is valid arithmetic operator in Python:
(i) // (ii) ? (iii) <(iv) and
Answer (i) //
2. Write the type of tokens from the following:
(i) if (ii) roll_no
Answer (i) Key word (ii) Identifier
(1/2 mark for each correct type)
3. Name the Python Library modules which need to be imported toinvoke
the
following functions:
(i) sin( ) (ii) randint ( )
Answer (i) math (ii) random
(1/2 mark for each module)
4 What do you understand by the term Iteration?
Answer Repeatation of statement/s finite number of times is known asIteration.
(1 mark for correct answer)
Answer 15
9 Find the valid identifier from the following
Answer s) S_name
Given the lists L=[1,3,6,82,5,7,11,92] , What will be the output of
print(L[2:5])
Answer [6,82,5]
a) ? b) < c) ** d) and
Answer d) and
Answer sqrt()
print(str[8:16])
Answer Vidyalay
19 Given the lists L=[“H”, “T”, “W”, “P”, “N”] , write the output of
print(L[3:4])
Answer [“N”]
20 What will be the output of: 1
print(10>20)
Answer False
2 MARKS QUESTIONS
1. Rewrite the following code in python after removing all syntax 2
error(s). Underline each correction done in the code.
30=To
for K in range(0,To)
IF k%4==0:
print (K*4)
Else:
print (K+3)
Answer To=30
for K in range(0,To) :
if k%4==0:
print (K*4)
else:
print (K+3)
(1/2 mark for each correction)
2. Find and write the output of the following python code: 2
def fun(s):
k=len(s)
m=" "
for i in range(0,k):
if(s[i].isupper()):
m=m+s[i].lower()
elif s[i].isalpha():
m=m+s[i].upper()
else:
m=m+'bb'
print(m)
fun('school2@com')
Answer SCHOOLbbbbCOM
(2 marks for correct output)
Note: Partial marking can also be given
3. What possible outputs(s) are expected to be displayed on screen at 2
the time of execution of the program from the following code? Also
specify the maximum values that can be assigned to each of the
variables FROM and TO.
import random
AR=[20,30,40,50,60,70];
FROM=random.randint(1,3)
TO=random.randint(2,4)
for K in range(FROM,TO+1):
print (AR[K],end=”# “)
import random
AR=[20,30,40,50,60,70];
Lower =random.randint(1,4)
Upper =random.randint(2,5)
print (AR[K],end=”#“)
Answer 51
True
10 What do you mean by keyword argument in python? Describe
with example.
Answer When you assign a value to the parameter (such as param=value)
and pass to the function (like fn(param=value)), then it turns into
a keyword argument.
11 Rewrite the following code in python after removing all
syntax errors. Underline each correction done in the code:
Def func(a):
for i in (0,a):
if i%2 =0:
s=s+1
else if i%5= =0
m=m+2
else:
n=n+i
print(s,m,n)
func(15)
Answer def func(a): #def
s=m=n=0 #local variable
for i in (0,a): #indentation and frange function missing
if i%2==0:
s=s+I
elif i%5==0: #elif and colon
m=m+i
else:
n=n+i
print(s,m,n) #indentation
func(15) 2 marks for any four corrections.
12 What possible outputs(s) are expected to be displayed on screen 2
at the time of execution of the program from the following code.
Select which option/s is/are correct
import random
print(random.randint(15,25) , end=' ')
print((100) + random.randint(15,25) , end = ' ' )
print((100) -random.randint(15,25) , end = ' ' )
print((100) *random.randint(15,25) )
(i) 15 122 84 2500
(ii) 21 120 76 1500
(iii) 105 107 105 1800
(iv) 110 105 105 1900
Answer (i ) (ii) are correct answers.
14 Predict the output of the following code. 2
def swap(P ,Q):
P,Q=Q,P
print( P,"#",Q)
return (P)
R=100
S=200
R=swap(R,S)
print(R,"#",S)
Answer
200 # 100
200 # 200
15 Evaluate the following expressions: 2
a) 6 * 3 + 4**2 // 5 – 8
b) 10 > 5 and 7 > 12 or not 18 > 3
Answer a) 13
c) False
output:
Inside add() : 12
In main: 15
(i) 10#40#70#
(ii) 30#40#50#
(iii) 50#60#70#
(iv) 40#50#70#
21 c = 10
def add():
global c
c=c+2
print("Inside add():", c)
add()
c=15
print("In main:", c)
output:
Inside add() : 12
In main: 15
Consider the above program and justify the output. What is the
output if “global c “ is not written in the function add().
import random as r
val = 35
P=7
Num = 0
for i in range(1, 5):
Num = val + r.randint(0, P - 1)
print(Num, " $ ", end = "")
P=P-1
(a) 41 $ 38 $ 38 $ 37 $ (b) 38 $ 40 $ 37 $ 34 $
(c) 36 $ 35 $ 42 $ 37 $ (d) 40 $ 37 $ 39 $ 35 $
Answer (a) 41 $ 38 $ 38 $ 37 $
(d) 40 $ 37 $ 39 $ 35 $
Maximum value of Num when P = 7 : 42
Minimum value of Num when P = 7 : 35
24 Find the output of the following program;
def increment(n):
n.append([4])
return n
l=[1,2,3]
m=increment(l)
print(l,m)
Answer [1, 2, 3, [4]] [1, 2, 3, [4]]
R=150
S=100
R=Change(R,S)
print(R,"#",S)
S=Change(S)
Answer 250 # 150
250 # 100
130 # 100
Answer L=len(Lst)
for x in range(0,n):
y=Lst[0]
for i in range(0,L-1):
Lst[i]=Lst[i+1]
Lst[L-1]=y
print(Lst)
#Note : Using of any correct code giving the same result
is also accepted.
arr=[10,20,23,45]
output : [10, 10, 115, 225]
Answer l=len(arr)
for a in range(l):
if(arr[a]%2==0):
arr[a]=10
else:
arr[a]=arr[a]*5
print(arr)
L=len(Arr)
for x in range(0,n):
y=Arr[0]
for i in range(0,L-1):
Arr[i]=Arr[i+1]
Arr[L-1]=y
print(Arr)
5 Write a program to reverse elements in a list where 3
arguments are start and end index of the list part which is
to be reversed. Assume that start<end, start>=0 and
end<len(list)
Sample Input Data of List
my_list=[1,2,3,4,5,6,7,8,9,10]
Output is
my_list=[1,2,3,7,6,5,4,8,9,10]
12
Answer my_mylist=[1,2,3,4,5,6,7,8,9,10]
l1=mylist[:start:1] ½ Mark
l2=mylist[end:start-1:-1] ½ Mark
l3=mylist[end+1:] ½ Mark
final_list=l1+l2+l3 ½ Mark
print (final_list) ½ Mark
Or any other relevant code
6 Write program to add those values in the list of 3
NUMBERS, which are odd.
Sample Input Data of the List
NUMBERS=[20,40,10,5,12,11]
OUTPUT is 16
Answer NUMBERS=[20,40,10,5,12,11]
s=0
for i in NUMBERS:
if i%2 !=0:
s=s+i
print(s)
7 Write a program to replaces elements having even values 3
with its half and elements having odd values with twice its
value in a list.
for i in range(n):
if L[i] % 2 == 0:
L[i] /= 2
else:
L[i] *= 2
print (L)
8 Write a Python program to find the maximum and minimum 3
elements in the list entered by the user.
Answer lst = []
num = int(input(“How many numbers”))
CHAPTER – 3 FUNCTIONS
Short Answer Type Questions – (1 mark for correct answer)
Q.1 Find and write the output of the following python code:
a=10
def call():
global a
a=15
call()
print(a)
Ans. 15
Q. 2. Trace the flow of execution for 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)
Ans. 1→5→9→10→6→2→3→7→11
def prod(x,y,z):
return x*y*z
a= addEm(6,16,26)
b= prod(2,3,6)
print(a,b)
Ans. 48
None 36.
Q2. To read the next line of the file from the file object infi, we use
a. infi.read(all)
b. infi.read()
c. infi.readline()
d. infi.readlines()
Q3. Which function is used to ensure that the data in written in the file
immediately?
a. <filehandle>.write()
b. <filehandle>.writelines()
c. flush()
d. <filehandle>.close()
Q4. What is the datatype of the value returned by readlines() function?
a. Integer
b. String
c. List of strings
d. None of the above
Q5. What is the position of the cursor when the file is opened in append mode?
a. Start of file
b. End of file
c. At the 11th byte
d. Unknown
Q6. How to open a file such that close function is not needed to be called in order
to close the connection between file and python program?
a. Using open() method
b. Using read() method
c. Using with keyword
d. Using open with method
7. What is the full form of CSV?
a. Common segregated values
b. Comma separated values
c. Common separated values
d. None of the above
Q9. If the cursor in the file is at the end of the file, then what will the read()
function return?
a. None
b. False
c. Exception
d. Empty string
Q10. Which is the value of mode parameter to set the offset of the cursor from the
end of the file?
a. 0
b. 1
c. 2
d. None of the above
Answer Key
1.d 2.c 3.c 4.c 5.b 6.c 7.b 8.a 9.d 10.c