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.
6. The function complex(‘2-3j’) is valid but the function complex(‘2 – 3j’) is invalid. State whether this statement is true or false.
a) True b) False
Answer: a
EXPLANATION: When converting from a string, the string must not contain any blank spaces around the + or – operator. Hence
the function complex(‘2 – 3j’) will result in an error.
10. Which of the following functions does not necessarily accept only iterables as arguments?
a) enumerate() b) all() c) chr() d) max()
Answer: c
EXPLANATION: The functions enumerate(), all() and max() accept iterables as arguments whereas the function chr() throws an
error on receiving an iterable as an argument. Also note that the function chr() accepts only integer values.
Python Question and Answers – Built-in Functions – 3
6. 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.
7. What is the output of the function shown below?
hex(15)
a) f b) 0xF c) 0Xf d) 0xf
Answer: d
EXPLANATION: The function hex() is used to convert the given argument into its hexadecimal representation, in lower case. Hence
the output of the function hex(15) is 0xf.
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.
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.
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.
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.
Python MCQ of – Global vs Local Variables – 2
1. Which of the following data structures is returned by the functions globals() and locals()?
a) list b) set c) dictionary d) tuple
Answer: c
EXPLANATION: Both the functions, that is, globals() and locals() return value of the data structure dictionary.
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.
3.Program code making use of a given module is called a ______ of the module.
a)Client b)Docstring
c)Interface d)Modularity
Answer: a
EXPLANATION: Program code making use of a given module is called the client of the module. There may be multiple clients
for a module.
4.______ is a string literal denoted by triple quotes for providing the specifications of certain program elements.
a)Interface b)Modularity c)Client d)Docstring
Answer: d
EXPLANATION: Docstring used for providing the specifications of program elements.
6. In top-down design every module is broken into same number of submodules? True or False?
a)True b)False
Answer: b
EXPLANATION: In top-down design every module can even be broken down into different number of submodules.
7.All modular designs are because of a top-down design process? True or False?
a)True b)False
Answer: b
EXPLANATION: The details of the program can be addressed before the overall design too. Hence, all modular designs are not
because of a top-down design process.
11. Which of the following is false about “import modulename” form of import?
a)The namespace of imported module becomes part of importing module
b)This form of import prevents name clash
c)The namespace of imported module becomes available to importing module
d)The identifiers in module are accessed as: modulename.identifier
Answer: a
EXPLANATION: In the “import modulename” form of import, the namespace of imported module becomes available to, but not
part of, the importing module.
15. What is the order of namespaces in which Python looks for an identifier?
a)Python first searches the global namespace, then the local namespace and finally the built-in namespace
b)Python first searches the local namespace, then the global namespace and finally the built-in namespace
c)Python first searches the built-in namespace, then the global namespace and finally the local namespace
d)Python first searches the built-in namespace, then the local namespace and finally the global namespace
Answer: b
EXPLANATION: Python first searches for the local, then the global and finally the built-in namespace.
Python MCQ of – Math Module – 1
5. 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.
8. 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.
6. What is x if x = math.isfinite(float(‘0.0’))?
a) True b) False c) None d) error
Answer: a
EXPLANATION: float(‘0.0’) is a finite number.
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’.
5. What is the output of the function shown below (random module has already been imported)?
random.choice('sun')
a) sun b) u c) either s, u or n d) error
Answer: c
EXPLANATION: The above function works with alphabets just as it does with numbers. The output of this expression will be
either s, u or n.
6. What is the output of the following function, assuming that the random module has already been imported?
random.uniform(3,4)
a) Error b) Either 3 or 4 c) Any integer other than 3 and 4
d) Any decimal value between 3 and 4
Answer: d
EXPLANATION: This question depicts the basic difference between the functions random.randint(a, b) and random.uniform(a,
b). While random.randint(a,b) generates an integer between ‘a’ and ‘b’, including ‘a’ and ‘b’, the function random.uniform(a,b)
generates a decimal value between ‘a’ and ‘b’.
7. What is the output of the function shown below if the random module has already been imported?
random.randint(3.5,7)
a) Error
b) Any integer between 3.5 and 7, including 7
c) Any integer between 3.5 and 7, excluding 7
d) The integer closest to the mean of 3.5 and 7
Answer: a
EXPLANATION: The function random.randint() does not accept a decimal value as a parameter. Hence the function shown above
will throw an error.
10. 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.
11. Which of the following is a possible outcome of the function shown below?
random.randrange(0,91,5)
a) 10 b) 18 c) 79 d) 95
Answer: a
EXPLANATION: The function shown above will generate an output which is a multiple of 5 and is between 0 and 91. The only
option which satisfies these criteria is 10. Hence the only possible output of this function is 10.
12. Both the functions randint and uniform accept ____________ parameters.
a) 0 b) 1 c) 3 d) 2
Answer: c
EXPLANATION: Both of these functions, that is, randint and uniform are included in the random module and both of these
functions accept 3 parameters. For example: random.uniform(self,a,b) where ‘a’ and ‘b’ specify the range and self is an imaginary
parameter.
13. 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.
14. 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.
15. What is the output of this function, assuming that the random library has already been included?
random.shuffle[1,2,24]
a) Randomized list containing the same numbers in any order
b) The same list, that is [1,2,24].
c) A list containing any random numbers between 1 and 24
d) Error
Answer: d
EXPLANATION: The function shown above will result in an error because this is the incorrect syntax for the usage of the function
shuffle(). The list should be previously declared and then passed to this function to get an output.
An example of the correct syntax:
>>> l=[‘a’,’b’,’c’,’d’].
>>> random.shuffle(l)
>>> print(l)
Python MCQ of – Random Module – 2
4. 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.
1. Which of the following functions can help us to find the version of python that we are currently working on?
a) sys.version b) sys.version()
c) sys.version(0) d) sys.version(1)
Answer: a
EXPLANATION: The function sys.version can help us to find the version of python that we are currently working on. For
example, 3.5.2, 2.7.3 etc. this function also returns the current date, time, bits etc along with the version.
2. Which of the following functions is not defined under the sys module?
a) sys.platform b) sys.path
c) sys.readline d) sys.argv
Answer: c
EXPLANATION: The functions sys.platform, sys.path and sys.argv are defined under the sys module. The function sys.readline
is not defined. However, sys.stdin.readline is defined.
3. The output of the functions len(“abc”) and sys.getsizeof(“abc”) will be the same. State whether true or false.
a) True b) False
Answer: b
EXPLANATION: The function len returns the length of the string passed, and hence it’s output will be 3. The function getsizeof,
present under the sys module returns the size of the object passed. It’s output will be a value much larger than 3. Hence the above
statement is false.
4. What is the output of the code shown below, if the code is run on Windows operating system?
import sys
if sys.platform[:2]== 'wi':
print("Hello")
a) Error b) Hello
c) No output d) Junk value
Answer: b
EXPLANATION: The output of the function sys.platform[:2] is equal to ‘wi’, when this code is run on windows operating system.
Hence the output printed is ‘hello’.
5. What is the output of the following line of code, if the sys module has already been imported?
sys.stdout.write("hello world")
a) helloworld b) hello world10c) hello world11d) error
Answer: c
EXPLANATION: The function shown above prints the given string along with the length of the string. Hence the output of the
function shown above will be hello world11.
6. Which of the following functions can be used to read data from a file using a file descriptor?
a) os.reader()
b) os.read()
c) os.quick_read()
d) os.scan()
Answer: b
EXPLANATION: None of the other functions exist.
7. Which of the following returns a string that represents the present working directory?
a) os.getcwd() b) os.cwd() c) os.getpwd() d) os.pwd()
Answer: a
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.
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.
1. Which are the two built-in functions to read a line of text from standard input, which by default comes from the keyboard?
a) Raw_input & Input b) Input & Scan
c) Scan & Scanner d) Scanner
Answer: a
EXPLANATION: Python provides two built-in functions to read a line of text from standard input, which by default comes from
the keyboard. These functions are:
raw_input and input
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.
Python MCQ of – Files – 5
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.
1. How many except statements can a try-except block have? c) only if some condition that has been specified is satisfied
a) zero b) one c) more than one d) more than zero d) always
Answer: d Answer: d
EXPLANATION: There has to be at least one except statement. EXPLANATION: The finally block is always executed.
2. When will the else part of try-except-else be executed? 7. What is the output of the following code?
a) always def foo():
b) when an exception occurs try:
c) when no exception occurs return 1
d) when an exception occurs in to except block finally:
Answer: c return 2
EXPLANATION: The else part is executed when no exception k = foo()
occurs. print(k)
3. Is the following code valid? a) 1 b) 2 c) 3
try: d) error, there is more than one return statement in a single
# Do something try-finally block
except: Answer: b
# Do something EXPLANATION: The finally block is executed even there is a
finally: return statement in the try block.
# Do something
a) no, there is no such thing as finally 8. What is the output of the following code?
b) no, finally cannot be used with except def foo():
c) no, finally must come before except try:
d) yes print(1)
Answer: b finally:
EXPLANATION: Refer documentation. print(2)
4. Is the following code valid? foo()
try: a) 1 2 b) 1 c) 2 d) none of the mentioned
# Do something Answer: a
except: EXPLANATION: No error occurs in the try block so 1 is
# Do something printed. Then the finally block is executed and 2 is printed.
else: 9. What is the output of the following?
# Do something try:
a) no, there is no such thing as else if '1' != 1:
b) no, else cannot be used with except raise "someError"
c) no, else must come before except else:
d) yes print("someError has not occurred")
Answer: d except "someError":
EXPLANATION: Refer documentation. print ("someError has occurred")
5. Can one block of except statements handle multiple a) someError has occurred
exception? b) someError has not occurred
a) yes, like except TypeError, SyntaxError [,…]. c) invalid code
b) yes, like except [TypeError, SyntaxError]. d) none of the mentioned
c) no Answer: c
d) none of the mentioned EXPLANATION: A new exception class must inherit from a
Answer: a BaseException. There is no such inheritance here.
EXPLANATION: Each type of exception can be specified 10. What happens when ‘1’ == 1 is executed?
directly. There is no need to put it in a list. a) we get a True
6. When is the finally block executed? b) we get a False
a) when there is no exception c) an TypeError occurs
b) when there is an exception d) a ValueError occurs
Answer: b EXPLANATION: It simply evaluates to False and does not
raise any exception.