Select Page
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages
Filter by Categories
nmims post
Objective Type Set
Online MCQ Assignment
Question Solution
Solved Question
Uncategorized

## Python MCQ Set 1

1. The following piece of code is invalid. True or False?

```class demo(dict):
def __test__(self,key):
return []
a = demo()
a['test'] = 7
print(a)```

a) True
b) False

Answer: b [Reason:] The output of the code is: {‘test’:7}.

2. What is the output of the following code?

```count={}
count[(1,2,4)] = 5
count[(4,2,1)] = 7
count[(1,2)] = 6
count[(4,2,1)] = 2
tot = 0
for i in count:
tot=tot+count[i]
print(len(count)+tot)```

a) 25
b) 17
c) 16
d) Tuples can’t be made keys of a dictionary

Answer: c [Reason:] Tuples can be made keys of a dictionary. Length of the dictionary is 3 as the value of the key (4,2,1) is modified to 2. The value of the variable tot is 5+6+2=13.

3. What is the output of the following code?

```a={}
a[2]=1
a[1]=[2,3,4]
print(a[1][1])```

a) [2,3,4].
b) 3
c) 2
d) An exception is thrown

Answer: b [Reason:] Now, a={1:[2,3,4],2:1} . a[1][1] refers to second element having key 1.

4. What is the output of the following piece of code?

```>>> a={'B':5,'A':9,'C':7}
>>> sorted(a)```

a) [‘A’,’B’,’C’].
b) [‘B’,’C’,’A’].
c) [5,7,9].
d) [9,5,7].

Answer: a [Reason:] Return a new sorted list of keys in the dictionary.

5. What is the output of the following snippet of code?

```>>> a={i: i*i for i in range(6)}
>>> a```

a) Dictionary comprehension doesn’t exist
b) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6:36}
c) {0: 0, 1: 1, 4: 4, 9: 9, 16: 16, 25: 25}
d) {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Answer: d [Reason:] Dictionary comprehension is implemented in the above piece of code.

6. What is the output of the following piece of code?

```>>> a={}
>>> a.fromkeys([1,2,3],"check")```

a) Syntax error
b) {1:”check”,2:”check”,3:”check”}
c) “check”
d) {1:None,2:None,3:None}

Answer: b [Reason:] The dictionary takes values of keys from the list and initializes it to the default value (value given in the second parameter). Execute in Python shell to verify.

7. What is the output of the following snippet of code?

```>>> b={}
>>> all(b)```

a) { }
b) False
c) True
d) An exception is thrown

Answer: c [Reason:] Function all() returns True if all keys of the dictionary are true or if the dictionary is empty.

8. If b is a dictionary, what does any(b) do?
a) Returns True if any key of the dictionary is true
b) Returns False if dictionary is empty
c) Returns True if all keys of the dictionary are true
d) Method any() doesn’t exist for dictionary

Answer: a [Reason:] Method any() returns True if any key of the dictionary is true and False if the dictionary is empty.

9. What is the output of the following code?

```>>> a={"a":1,"b":2,"c":3}
>>> b=dict(zip(a.values(),a.keys()))
>>> b```

a) {‘a’: 1, ‘b’: 2, ‘c’: 3}
b) An exception is thrown
c) {‘a’: ‘b’: ‘c’: }
d) {1: ‘a’, 2: ‘b’, 3: ‘c’}

Answer: d [Reason:] The above piece of code inverts the key-value pairs in the dictionary.

10. What is the output of the following piece of code when executed in Python shell?

```>>> a={i: 'A' + str(i) for i in range(5)}
>>> a```

a) An exception is thrown
b) {0: ‘A0’, 1: ‘A1’, 2: ‘A2’, 3: ‘A3’, 4: ‘A4’}
c) {0: ‘A’, 1: ‘A’, 2: ‘A’, 3: ‘A’, 4: ‘A’}
d) {0: ‘0’, 1: ‘1’, 2: ‘2’, 3: ‘3’, 4: ‘4’}

Answer: d [Reason:] Dictionary comprehension and string concatenation is implemented in the above piece of code.

11. What is the output of the following piece of code when executed in Python shell?

```>>> a=dict()
>>> a[1]```

a) An exception is thrown since the dictionary is empty
b) ‘ ‘
c) 1
d) 0

Answer: a [Reason:] The values of a dictionary can be accessed through the keys only if the keys exist in the dictionary.

12. What is the output of the following piece of code when executed in Python shell?

```>>> import collections
>>> a=dict()
>>> a=collections.defaultdict(int)
>>> a[1]```

a) 1
b) 0
c) An exception is thrown
d) ‘ ‘

Answer: b [Reason:] The statement a=collections.defaultdict(int) gives the default value of 0 (since int data type is given within the parenthesis) even if the keys don’t exist in the dictionary.

13. What is the output of the following piece of code when executed in Python shell?

```>>> import collections
>>> a=dict()
>>> a=collections.defaultdict(str)
>>> a['A']```

a) An exception is thrown since the dictionary is empty
b) ‘ ‘
c) ‘A’
d) 0

Answer: b [Reason:] The statement a=collections.defaultdict(str) gives the default value of ‘ ‘ even if the keys don’t exist in the dictionary.

14. What is the output of the following piece of code when executed in Python shell?

```>>> import collections
>>> b=dict()
>>> b=collections.defaultdict(lambda: 7)
>>> b[4]```

a) 4
b) 0
c) An exception is thrown
d) 7

Answer: d [Reason:] The statement a=collections.defaultdict(lambda: x) gives the default value of x even if the keys don’t exist in the dictionary.

15. What is the output of the following piece of code when executed in Python shell?

```>>> import collections
>>> a=collections.OrderedDict((str(x),x) for x in range(3))
>>> a```

a) {‘2’:2, ‘0’:0, ‘1’:1}
b) OrderedDict([(‘0’, 0), (‘1’, 1), (‘2’, 2)])
c) An exception is thrown
d) ‘ ‘

Answer: b [Reason:] The line of code a=collections.OrderedDict() generates a dictionary satisfying the conditions given within the parenthesis and in an ascending order of the keys.

## Python MCQ Set 2

1. Which of these is not a fundamental features of OOP?
a) Encapsulation
b) Inheritance
c) Instantiation
d) Polymorphism

Answer: c [Reason:] Instantiation simply refers to creation of an instance of class. It is not a fundamental feature of OOP.

2. Which of the following is the most suitable definition for encapsulation?
a) Ability of a class to derive members of another class as a part of its own definition
b) Means of bundling instance variables and methods in order to restrict access to certain class members
c) Focuses on variables and passing of variables to functions
d) Allows for implementation of elegant software that is well designed and easily modified

Answer: b [Reason:] The values assigned by the constructor to the class members is used to create the object.

3. What is the output of the following code?

```class Demo:
def __init__(self):
self.a = 1
self.__b = 1

def display(self):
return self.__b
obj = Demo()
print(obj.a)```

a) The program has an error because there isn’t any function to return self.a
b) The program has an error because b is private and display(self) is returning a private member
c) The program runs fine and 1 is printed
d) The program has an error as you can’t name a class member using __b

Answer: c [Reason:] The program has no error because the class member which is public is printed. 1 is displayed. Execute in python shell to verify.

4. What is the output of the following code?

```class Demo:
def __init__(self):
self.a = 1
self.__b = 1

def display(self):
return self.__b

obj = Demo()
print(obj.__b)```

a) The program has an error because there isn’t any function to return self.a
b) The program has an error because b is private and display(self) is returning a private member
c) The program has an error because b is private and hence can’t be printed
d) The program runs fine and 1 is printed

Answer: c [Reason:] Variables beginning with two underscores are said to be private members of the class and they can’t be accessed directly.

5. Methods of a class that provide access to private members of the class are called as ______ and ______
a) getters/setters
b) __repr__/__str__
c) user-defined functions/in-built functions
d) __init__/__del__

Answer: a [Reason:] The purpose of getters and setters is to get(return) and set(assign) private instance variables of a class.

6. Which of these is a private data field?

```def Demo:
def __init__(self):
__a = 1
self.__b = 1
self.__c__ = 1
__d__= 1```

a) __a
b) __b
c) __c__
d) __d__

Answer: b [Reason:] Variables such as self.__b are private members of the class.

7. What is the output of the following code?

```class Demo:
def __init__(self):
self.a = 1
self.__b = 1

def get(self):
return self.__b

obj = Demo()
print(obj.get())```

a) The program has an error because there isn’t any function to return self.a
b) The program has an error because b is private and display(self) is returning a private member
c) The program has an error because b is private and hence can’t be printed
d) The program runs fine and 1 is printed

Answer: d [Reason:] Here, get(self) is a member of the class. Hence, it can even return a private member of the class. Because of this reason, the program runs fine and 1 is printed.

8. What is the output for the following piece of code?

```class Demo:
def __init__(self):
self.a = 1
self.__b = 1
def get(self):
return self.__b
obj = Demo()
obj.a=45
print(obj.a)```

a) The program runs properly and prints 45
b) The program has an error because the value of members of a class can’t be changed from outside the class
c) The program runs properly and prints 1
d) The program has an error because the value of members outside a class can only be changed as self.a=45

Answer: a [Reason:] It is possible to change the values of public class members using the object of the class.

9. Private members of a class cannot be accessed. True or False?
a) True
b) False

Answer: b [Reason:] Private members of a class are accessible if written as follows: obj._Classname__privatemember. Such renaming of identifiers is called as name mangling.

10. The purpose of name mangling is to avoid unintentional access of private class members. True or False?
a) True
b) False

Answer: a [Reason:] Name mangling prevents unintentional access of private members of a class, while still allowing access when needed. Unless the variable is accessed with its mangled name, it will not be found.

11. What is the output of the following code?

```class fruits:
def __init__(self):
self.price = 100
self.__bags = 5
def display(self):
print(self.__bags)
obj=fruits()
obj.display()```

a) The program has an error because display() is trying to print a private class member
b) The program runs fine but nothing is printed
c) The program runs fine and 5 is printed
d) The program has an error because display() can’t be accessed

Answer: c [Reason:] Private class members can be printed by methods which are members of the class.

12. What is the output of the following code?

``` class student:
def __init__(self):
self.marks = 97
self.__cgpa = 8.7
def display(self):
print(self.marks)
obj=student()
print(obj._student__cgpa)```

a) The program runs fine and 8.7 is printed
b) Error because private class members can’t be accessed
c) Error because the proper syntax for name mangling hasn’t been implemented
d) The program runs fine but nothing is printed

Answer: a [Reason:] Name mangling has been properly implemented in the code given above and hence the program runs properly.

13. Which of the following is false about protected class members?
a) They begin with one underscore
b) They can be accessed by subclasses
c) They can be accessed by name mangling method
d) They can be accessed within a class

Answer: c [Reason:] Protected class members can’t be accessed by name mangling.

14. What is the output of the following piece of code?

```class objects:
def __init__(self):
self.colour = None
self._shape = "Circle"

def display(self, s):
self._shape = s
obj=objects()
print(obj._objects_shape)```

a) The program runs fine because name mangling has been properly implemented
b) Error because the member shape is a protected member
c) Error because the proper syntax for name mangling hasn’t been implemented
d) Error because the member shape is a private member

Answer: b [Reason:] Protected members begin with one underscore and they can only be accessed within a class or by subclasses.

## Python MCQ Set 3

1. How many except statements can a try-except block have?
a) zero
b) one
c) more than one
d) more than zero

Answer: d [Reason:] There has to be at least one except statement.

2. When will the else part of try-except-else be executed?
a) always
b) when an exception occurs
c) when no exception occurs
d) when an exception occurs in to except block

Answer: c [Reason:] The else part is executed when no exception occurs.

3. Is the following code valid?

```try:
# Do something
except:
# Do something
finally:
# Do something```

a) no, there is no such thing as finally
b) no, finally cannot be used with except
c) no, finally must come before except
d) yes

4. Is the following code valid?

```try:
# Do something
except:
# Do something
else:
# Do something```

a) no, there is no such thing as else
b) no, else cannot be used with except
c) no, else must come before except
d) yes

5. Can one block of except statements handle multiple exception?
a) yes, like except TypeError, SyntaxError [,…].
b) yes, like except [TypeError, SyntaxError].
c) no
d) none of the mentioned

Answer: a [Reason:] Each type of exception can be specified directly. There is no need to put it in a list.

6. When is the finally block executed?
a) when there is no exception
b) when there is an exception
c) only if some condition that has been specified is satisfied
d) always

Answer: d [Reason:] The finally block is always executed.

7. What is the output of the following code?

```def foo():
try:
return 1
finally:
return 2
k = foo()
print(k)```

a) 1
b) 2
c) 3
d) error, there is more than one return statement in a single try-finally block

Answer: b [Reason:] The finally block is executed even there is a return statement in the try block.

8. What is the output of the following code?

```def foo():
try:
print(1)
finally:
print(2)
foo()```

a) 1 2
b) 1
c) 2
d) none of the mentioned

Answer: a [Reason:] No error occurs in the try block so 1 is printed. Then the finally block is executed and 2 is printed.

9. What is the output of the following?

```try:
if '1' != 1:
raise "someError"
else:
print("someError has not occured")
except "someError":
print ("someError has occured")```

a) someError has occured
b) someError has not occured
c) invalid code
d) none of the mentioned

Answer: c [Reason:] A new exception class must inherit from a BaseException. There is no such inheritance here.

10. What happens when ‘1’ == 1 is executed?
a) we get a True
b) we get a False
c) an TypeError occurs
d) a ValueError occurs

Answer: b [Reason:] It simply evaluates to False and does not raise any exception.

## Python MCQ Set 4

1. The code shown below will result in an error if the input value is entered as -5. State whether this statement is true or false.

`assert False, 'Spanish'`

a) True
b) False

Answer: a [Reason:] The code shown above results in an assertion error. The output of the code is: Traceback (most recent call last): File “ “, line 1, in assert False, ‘Spanish’ AssertionError: Spanish Hence, this statement is true.

2. What is the output of the code shown below?

```x=10
y=8
assert x>y, 'X too small'```

a) Assertion Error
b) 10 8
c) No output
d) 108

Answer: c [Reason:] The code shown above results in an error if and only if xy, there is no error. Since there is no print statement, hence there is no output.

3. What is the output of the code shown below?

```#generator
def f(x):
yield x+1
g=f(8)
print(next(g))```

a) 8
b) 9
c) 7
d) Error

Answer: b [Reason:] The code shown above returns the value of the expression x+1, since we have used to keyword yield. The value of x is 8. Hence the output of the code is 9.

4. What is the output of the code shown below?

```def f(x):
yield x+1
print("test")
yield x+2
g=f(9)```

a) Error
b) test
c) test
10
12
d) No output

Answer: d [Reason:] The code shown above will not yield any output. This is because when we try to yield 9, and there is no next(g), the iteration stops. Hence there is no output.

5. What is the output of the code shown below?

```def f(x):
yield x+1
print("test")
yield x+2
g=f(10)
print(next(g))
print(next(g))```

a) No output
b) 11
test
12
c) 11
test
d) 11

Answer: b [Reason:] The code shown above results in the output: 11 test 12 This is because we have used next(g) twice. Had we not used next, there would be no output.

6. What is the output of the following code?

```def a():
try:
f(x, 4)
finally:
print('after f')
print('after f?')
a()```

a) No output
b) after f?
c) error
d) after f

Answer: c [Reason:] This code shown above will result in an error simply because ‘f’ is not defined. ‘try’ and ‘finally’ are keywords used in exception handling.

7. What is the output of the code shown?

```def f(x):
for i in range(5):
yield i
g=f(8)
print(list(g))```

a) [0, 1, 2, 3, 4]
b) [1, 2, 3, 4, 5, 6, 7, 8]
c) [1, 2, 3, 4, 5]
d) [0, 1, 2, 3, 4, 5, 6, 7]

Answer: a [Reason:] The output of the code shown above is a list containing whole numbers in the range (5). Hence the output of this code is: [0, 1, 2, 3, 4].

8. The error displayed in the code shown below is:

```import itertools
l1=(1, 2, 3)
l2=[4, 5, 6]
l=itertools.chain(l1, l2)
print(next(l1))```

a) ‘list’ object is not iterator
b) ‘tuple’ object is not iterator
c) ‘list’ object is iterator
d) ‘tuple’ object is iterator

Answer: b [Reason:] The error raised in the code shown above is that: ‘tuple’ object is not iterator. Had we given l2 as argument to next, the error would have been: ‘list’ object is not iterator.

9. Which of the following is not an exception handling keyword in Python?
a) try
b) except
c) accept
d) finally

Answer: c [Reason:] The keywords ‘try’, ‘except’ and ‘finally’ are exception handling keywords in python whereas the word ‘accept’ is not a keyword at all.

10. What is the output of the code shown below?

```g = (i for i in range(5))
type(g)```

a) class <’loop’>
b) class <‘iteration’>
c) class <’range’>
d) class <’generator’>

Answer: d [Reason:] Another way of creating a generator is to use parenthesis. Hence the output of the code shown above is: class<’generator’>.

## Python MCQ Set 5

1. What happens if the file is not found in the code shown below?

```a=False
while not a:
try:
f_n = input("Enter file name")
i_f = open(f_n, 'r')
except:

a) No error
b) Assertion error
c) Input output error
d) Name error

Answer: a [Reason:] In the code shown above, if the input file in not found, then the statement: “Input file not found” is printed on the screen. The user is then prompted to reenter the file name. Error is not thrown.

2. What is the output of the code shown below?

```lst = [1, 2, 3]
lst[3]```

a) NameError
b) ValueError
c) IndexError
d) TypeError

Answer: c [Reason:] The snippet of code shown above throws an index error. This is because the index of the list given in the code, that is, 3 is out of range. The maximum index of this list is 2.

3. What is the output of the code shown below?

`t[5]`

a) IndexError
b) NameError
c) TypeError
d) ValeError

Answer: b [Reason:] The expression shown above results in a name error. This is because the name ‘t’ is not defined.

4. What is the output of the following code, if the time module has already been imported?

`4 + '3'`

a) NameError
b) IndexError
c) ValueError
d) TypeError

Answer: d [Reason:] The line of code shown above will result in a type error. This is because the operand ‘+’ is not supported when we combine the data types ‘int’ and ‘str’. Sine this is exactly what we have done in the code shown above, a type error is thrown.

5. The output of the code shown below is:

`int('65.43')`

a) ImportError
b) ValueError
c) TypeError
d) NameError

Answer: b [Reason:] The snippet of code shown above results in a value error. This is because there is an invalid literal for int() with base 10: ’65.43’.

6. Compare the two codes shown below and state the output if the input entered in each case is -6?

```CODE 1
import math
num=int(input("Enter a number of whose factorial you want to find"))
print(math.factorial(num))

CODE 2
num=int(input("Enter a number of whose factorial you want to find"))
print(math.factorial(num))```

a) ValueError, NameError
b) AttributeError, ValueError
c) NameError, TypeError
d) TypeError, ValueError

Answer: a [Reason:] The first code results in a ValueError. This is because when we enter the input as -6, we are trying to find the factorial of a negative number, which is not possible. The second code results in a NameError. This is because we have not imported the math module. Hence the name ‘math’ is undefined.

7. What is the output of the code shown below?

```def getMonth(m):
if m<1 or m>12:
raise ValueError("Invalid")
print(m)
getMonth(6)```

a) ValueError
b) Invalid
c) 6
d) ValueError(“Invalid”)

Answer: c [Reason:] In the code shown above, since the value passed as an argument to the function is between 1 and 12 (both included), hence the output is the value itself, that is 6. If the value had been above 12 and less than 1, a ValueError would have been thrown.

8. What is the output of the code shown below if the input entered is 6?

```valid = False
while not valid:
try:
n=int(input("Enter a number"))
while n%2==0:
print("Bye")
valid = True
except ValueError:
print("Invalid")```

a) Bye (printed once)
b) No output
c) Invalid (printed once)
d) Bye (printed infinite number of times)

Answer: d [Reason:] The code shown above results in the word “Bye” being printed infinite number of times. This is because an even number has been given as input. If an odd number had been given as input, then there would have been no output.

9. Identify the type of error in the codes shown below.

```Print(“Good Morning”)
print(“Good night)```

a) Syntax, Syntax
b) Semantic, Syntax
c) Semantic, Semantic
d) Syntax, Semantic

Answer: b [Reason:] The first code shows an error detected during execution. This might occur occasionally. The second line of code represents a syntax error. When there is deviation from the rules of a language, a syntax error is thrown.

10. Which of the following statements is true?
a) The standard exceptions are automatically imported into Python programs
b) All raised standard exceptions must be handled in Python
c) When there is a deviation from the rules of a programming language, a semantic error is thrown
d) If any exception is thrown in try block, else block is executed

Answer: a [Reason:] When any exception is thrown in try block, except block is executed. If exception in not thrown in try block, else block is executed. When there is a deviation from the rules of a programming language, a syntax error is thrown. The only true statement above is: The standard exceptions are automatically imported into Python programs.

11. Which of the following is not a standard exception in Python?
a) NameError
b) IOError
c) AssignmentError
d) ValueError

Answer: c [Reason:] NameError, IOError and ValueError are standard exceptions in Python whereas Assignment error is not a standard exception in Python.

12. Syntax errors are also known as parsing errors. Is this statement true or false?
a) True
b) False

Answer: a [Reason:] Syntax errors are known as parsing errors. Syntax errors are raised when there is a deviation from the rules of a language. Hence the statement is true.

13. An exception is:
a) an object
b) a special function
c) a standard module
d) a module

Answer: a [Reason:] An exception is an object that is raised by a function signaling that an unexpected situation has occurred, that the function itself cannot handle.

14. _______________________ exceptions are raised as a result of an error in opening a particular file.
a) ValueError
b) TypeError
c) ImportError
d) IOError

Answer: d [Reason:] IOError exceptions are raised as a result of an error in opening or closing a particular file.

15. Which of the following blocks will be executed whether an exception is thrown or not?
a) except
b) else
c) finally
d) assert