Python MCQs

Python MCQs. This Section contains Multiple Choice Questions related to all major and minor topics in the Python Programming language. These topics include Variables, Operators, Core Data Types, Argument Passing, Dictionary, Files, Deepcopy, Shallowcopy, Bitwise, Formatting, Strings, While loops, For loops, List, Tuples, Sets, Functions, Mapping FUnctions, Regular expressions and many more.

Python Object Oriented: OOP Questions in Python

Python Object Oriented. This section contains Multiple Choice Questions on Python Object Oriented concepts.

Python Object Oriented

 

Which of the following statements is wrong about inheritance ??

a) Protected members of a class can be inherited
b) The inheriting class is called a subclass
c) Private members of a class can be inherited and accessed
d) Inheritance is one of the features of OOP

 

What will be the answer ??

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

 

What will be the output of the following ??

class Demo:
def __init__(self):
self.x = 1
def change(self):
self.x = 10
class Demo_derived(Demo):
def change(self):
self.x=self.x+1
return self.x
def main():
obj = Demo_derived()
print(obj.change())
main()

a) 11
b) 2
c) 1
d) An exception is thrown

 

What will be the output of the code ??

class A:
def __init__(self):
self.__i = 1
self.j = 5

def display(self):
print(self.__i, self.j)
class B(A):
def __init__(self):
super().__init__()
self.__i = 2
self.j = 7
c = B()
c.display()

a) 2 7
b) 1 5
c) 1 7
d) 2 5

Python Object Oriented

 

Which of the following best describes inheritance ??

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

 

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

 

What will be the output of the following Python ??

class A:
def __str__(self):
return ‘1’
class B(A):
def __init__(self):
super().__init__()
class C(B):
def __init__(self):
super().__init__()
def main():
obj1 = B()
obj2 = A()
obj3 = C()
print(obj1, obj2,obj3)
main()

a) 1 1 1
b) 1 2 3
c) ‘1’ ‘1’ ‘1’
d) An exception is thrown

 

What does single-level inheritance mean ??

a) A subclass derives from a class which in turn derives from another class
b) A single superclass inherits from multiple subclasses
c) A single subclass derives from a single superclass
d) Multiple base classes inherit a single derived class

 

Python Object Oriented

 

Which of these is not a fundamental features of OOP ??

a) Encapsulation
b) Inheritance
c) Instantiation
d) Polymorphism

 

What is the use of duck typing ??

a) More restriction on the type values that can be passed to a given method
b) No restriction on the type values that can be passed to a given method
c) Less restriction on the type values that can be passed to a given method
d) Makes the program code smaller

 

What type of inheritance is illustrated in the following Python code ??

class A():
pass
class B(A):
pass
class C(B):
pass

a) Multi-level inheritance
b) Multiple inheritance
c) Hierarchical inheritance
d) Single-level inheritance

 

Which of the following best describes polymorphism ??

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 objects of different types and behaviour to be treated as the same general type

 

What is the biggest reason for the use of polymorphism ??

a) It allows the programmer to think at a more abstract level
b) There is less program code to write
c) The program will have a more elegant design and will be easier to maintain and update
d) Program code takes up less space

OOPs In Python: OOP MCQs in Python

OOPs In Python. Questions And Answers Exercise on Concepts of OOPs In Python language.

OOPs In Python

 

Python is object oriented programming language ??

a) True
b) False

 

What will be the output of the following Python ??

class A():
def disp(self):
print(“A disp()”)
class B(A):
pass
obj = B()
obj.disp()

a) Invalid syntax for inheritance
b) Error because when object is created, argument must be passed
c) Nothing is printed
d) A disp()

 

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__

 

What will be the output of the ??

class A:
def __repr__(self):
return “1”
class B(A):
def __repr__(self):
return “2”
class C(B):
def __repr__(self):
return “3”
o1 = A()
o2 = B()
o3 = C()
print(obj1, obj2, obj3)

a) 1 1 1
b) 1 2 3
c) ‘1’ ‘1’ ‘1’
d) An exception is thrown

OOPs In Python

What will be the output of the following ??

>>> class A:
pass
>>> class B(A):
pass
>>> obj=B()
>>> isinstance(obj,A)

a) True
b) False
c) Wrong syntax for isinstance() method
d) Invalid method for classes

 

What will be the output of Python code ??

class Test:
def __init__(self):
self.x = 0
class Derived_Test(Test):
def __init__(self):
self.y = 1
def main():
b = Derived_Test()
print(b.x,b.y)
main()

a) 0 1
b) 0 0
c) Error because class B inherits A but variable x isn’t inherited
d) Error because when object is created, argument must be passed like Derived_Test(1)

 

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__

 

Overriding means changing behaviour of methods of derived class methods in the base class ??

a) True
b) False

OOPs In Python

What will be the output of ??

class A:
def __init__(self,x):
self.x = x
def count(self,x):
self.x = self.x+1
class B(A):
def __init__(self, y=0):
A.__init__(self, 3)
self.y = y
def count(self):
self.y += 1
def main():
obj = B()
obj.count()
print(obj.x, obj.y)
main()

a) 3 0
b) 3 1
c) 0 1
d) An exception in thrown

 

What is the output ??

class Demo:
def __new__(self):
self.__init__(self)
print(“Demo’s __new__() invoked”)
def __init__(self):
print(“Demo’s __init__() invoked”)
class Derived_Demo(Demo):
def __new__(self):
print(“Derived_Demo’s __new__() invoked”)
def __init__(self):
print(“Derived_Demo’s __init__() invoked”)
def main():
obj1 = Derived_Demo()
obj2 = Demo()
main()

 

a) Derived_Demo’s __init__() invoked
Derived_Demo’s __new__() invoked
Demo’s __init__() invoked
Demo’s __new__() invoked

b) Derived_Demo’s __new__() invoked
Demo’s __init__() invoked
Demo’s __new__() invoked

c) Derived_Demo’s __new__() invoked
Demo’s __new__() invoked

d) Derived_Demo’s __init__() invoked
Demo’s __init__() invoked

 

What will be the output of the 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

 

A class in which one or more methods are only implemented to raise an exception is called an abstract class ??

a) True
b) False

 

Which of the following statements isn’t true ??

a) A non-private method in a superclass can be overridden
b) A derived class is a subset of superclass
c) The value of a private variable in the superclass can be changed in the subclass
d) When invoking the constructor from a subclass, the constructor of superclass is automatically invoked

OOPs Concepts In Python: OOP MCQs In Python

OOPs Concepts In Python. MCQs on OOPs Concepts In Python Programming Language.

 

OOPs Concepts In Python

 

 

What will be the output of the following Python code ??

class A:
def __init__(self):
self._x = 5
class B(A):
def display(self):
print(self._x)
def main():
obj = B()
obj.display()
main()

a) Error, invalid syntax for object declaration
b) Nothing is printed
c) 5
d) Error, private class member can’t be accessed in a subclass

 

What will be the output ??

class Test:
def __init__(self):
self.x = 0
class Derived_Test(Test):
def __init__(self):
Test.__init__(self)
self.y = 1
def main():
b = Derived_Test()
print(b.x,b.y)
main()

a) Error because class B inherits A but variable x isn’t inherited
b) 0 0
c) 0 1
d) Error, the syntax of the invoking method is wrong

 

The purpose of name mangling is to avoid unintentional access of private class members ??

a) True
b) False

 

What will be the output of the code ??

class A:
def __init__(self):
self.multiply(15)
def multiply(self, i):
self.i = 4 * i;
class B(A):
def __init__(self):
super().__init__()
print(self.i)

def multiply(self, i):
self.i = 2 * i;
obj = B()

a) 15
b) 30
c) An exception is thrown
d) 60

 

OOPs Concepts In Python

 

What is the output ??

class A:
def __init__(self):
self.__x = 1
class B(A):
def display(self):
print(self.__x)
def main():
obj = B()
obj.display()
main()

a) 1
b) 0
c) Error, invalid syntax for object declaration
d) Error, private class member can’t be accessed in a subclass

 

Suppose B is a subclass of A, to invoke the __init__ method in A from B, what is the line of code you should write ??

a) A.__init__(self)
b) B.__init__(self)
c) A.__init__(B)
d) B.__init__(A)

 

Private members of a class cannot be accessed ??

a) True
b) False

 

What will be the output of the ??

class Demo:
def check(self):
return ” Demo’s check ”
def display(self):
print(self.check())
class Demo_Derived(Demo):
def check(self):
return ” Derived’s check “
Demo().display()
Demo_Derived().display()

 

a) Demo’s check Derived’s check
b) Demo’s check Demo’s check
c) Derived’s check Demo’s check
d) Syntax error

 

OOPs Concepts In Python

 

Method issubclass() checks if a class is a subclass of another class ??

a) True
b) False

 

When defining a subclass in Python that is meant to serve as a subtype, the subtype Python keyword is used ??

a) True
b) False

 

What will be the output of the following Python 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

 

What will be the output of the following Python ??

class A:
def __init__(self):
self.multiply(15)
print(self.i)

def multiply(self, i):
self.i = 4 * i;
class B(A):
def __init__(self):
super().__init__()

def multiply(self, i):
self.i = 2 * i;
obj = B()

a) 15
b) 60
c) An exception is thrown
d) 30

 

OOPs Concepts In Python

 

Which of the following statements is true ??

a) The __new__() method automatically invokes the __init__ method
b) The __init__ method is defined in the object class
c) The __eq(other) method is defined in the object class
d) The __repr__() method is defined in the object class

 

All subclasses are a subtype in object-oriented programming ??

a) True
b) False

 

What will be the output ??

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

Python For OOP: Python MCQs On OOP

Python For OOP. Multiple Choice Questions on OOP concepts with Python coding examples and Questions/Answers.

 

Python For OOP

 

 

What does built-in function help do in context of classes ??

a) Determines the object name of any value
b) Determines the class identifiers of any value
c) Determines class description of any built-in type
d) Determines class description of any user-defined built-in type

 

What will be the output of the 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

 

Which of the following statements is true ??

a) A non-private method in a superclass can be overridden
b) A subclass method can be overridden by the superclass
c) A private method in a superclass can be overridden
d) Overriding isn’t possible in Python

 

What will be the output of the following Python ??

class A:
def test(self):
print(“test of A called”)
class B(A):
def test(self):
print(“test of B called”)
super().test()
class C(A):
def test(self):
print(“test of C called”)
super().test()
class D(B,C):
def test2(self):
print(“test of D called”)
obj=D()
obj.test()

 

a) test of B called
test of C called
test of A called

b) test of C called
test of B called

c) test of B called
test of C called

d) Error, all the three classes from which D derives has same method test()

 

Python For OOP

 

Which of the following is not a type of inheritance ??

a) Double-level
b) Multi-level
c) Single-level
d) Multiple

 

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

 

What will be the output of the following ??

class A:
def one(self):
return self.two()
def two(self):
return ‘A’
class B(A):
def two(self):
return ‘B’
obj2=B()
print(obj2.two())

 

a) A
b) An exception is thrown
c) A B
d) B

 

What will be the output ??

class A:
def test1(self):
print(” test of A called “)
class B(A):
def test(self):
print(” test of B called “)
class C(A):
def test(self):
print(” test of C called “)
class D(B,C):
def test2(self):
print(” test of D called “)
obj=D()
obj.test()

 

a) test of B called
test of C called

b) test of C called
test of B called

 

c) test of B called

 

d) Error, both the classes from which D derives has same method test()

 

Python For OOP

 

What does built-in function type do in context of classes ??

a) Determines the object name of any value
b) Determines the class name of any value
c) Determines class description of any value
d) Determines the file name of any value

 

What will be the output of the ??

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

 

What will be the output of code ??

class A:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return 1
def __eq__(self, other):
return self.x * self.y == other.x * other.y
obj1 = A(5, 2)
obj2 = A(2, 5)
print(obj1 == obj2)

 

a) False
b) 1
c) True
d) An exception is thrown

 

What will be the output of the following Python code ??

class A:
def __init__(self,x=3):
self._x = x
class B(A):
def __init__(self):
super().__init__(5)
def display(self):
print(self._x)
def main():
obj = B()
obj.display()
main()

 

a) 5
b) Error, class member x has two values
c) 3
d) Error, protected class member can’t be accessed in a subclass

 

Python For OOP

 

What will be the output of code ??

class A:
def __init__(self, x= 1):
self.x = x
class der(A):
def __init__(self,y = 2):
super().__init__()
self.y = y
def main():
obj = der()
print(obj.x, obj.y)
main()

a) Error, the syntax of the invoking method is wrong
b) The program runs fine but nothing is printed
c) 1 0
d) 1 2

 

What will be the output ??

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

 

What will be the output of the Python code ??

class Demo:
def __check(self):
return ” Demo’s check “
def display(self):
print(self.check())
class Demo_Derived(Demo):
def __check(self):
return ” Derived’s check “
Demo().display()
Demo_Derived().display()

a) Demo’s check Derived’s check
b) Demo’s check Demo’s check
c) Derived’s check Demo’s check
d) Syntax error

Python OOP: MCQs On OOP In Python

Python OOP. MCQs related to OOP concepts in Python language.

 

Python OOP

 

 

What will be the output of the following Python code ??

>>> class demo():
def __repr__(self):
return ‘__repr__ built-in function called’
def __str__(self):
return ‘__str__ built-in function called’
>>> s=demo()
>>> print(s)

a) Error
b) Nothing is printed
c) __str__ called
d) __repr__ called

 

What is getattr() used for ??

a) To access the attribute of the object
b) To delete an attribute
c) To check if an attribute exists or not
d) To set an attribute

 

Special methods need to be explicitly called during object creation ??

a) True
b) False

 

What is setattr() used for ??

a) To access the attribute of the object
b) To set an attribute
c) To check if an attribute exists or not
d) To delete an attribute

 

Python OOP

 

What are the methods which begin and end with two underscore characters called ??

a) Special methods
b) In-built methods
c) User-defined methods
d) Additional methods

 

What will be the output ??

class test:
def __init__(self,a=”Hello World”):
self.a=a

def display(self):
print(self.a)
obj=test()
obj.display()

 

a) The program has an error because constructor can’t have default arguments
b) Nothing is displayed
c) “Hello World” is displayed
d) The program has an error display function doesn’t have parameters

 

Is the following Python code valid ??

class B(object):
def first(self):
print(“First method called”)
def second():
print(“Second method called”)
ob = B()
B.first(ob)

a) It isn’t as the object declaration isn’t right
b) It isn’t as there isn’t any __init__ method for initializing class members
c) Yes, this method of calling is called unbounded method call
d) Yes, this method of calling is called bounded method call

 

What is used to create an object ??

a) class
b) constructor
c) User-defined functions
d) In-built functions

 

Python OOP

 

Which of the following Python code creates an empty class ??

a) class A:
return

b) class A:
pass

c) class A:

d) It is not possible to create an empty class

 

What represents an entity in the real world with its identity and behaviour ??

a) A method
b) An object
c) A class
d) An operator

 

What will be the output of the following code ??

def add(c,k):
c.test=c.test+1
k=k+1
class A:
def __init__(self):
self.test = 0
def main():
Count=A()
k=0

for i in range(0,25):
add(Count,k)
print(“Count.test=”, Count.test)
print(“k =”, k)
main()

a) Exception is thrown

b) Count.test=25
k=25

c) Count.test=25
k=0

d) Count.test=0
k=0

 

What type of inheritance is illustrated in the following Python code ??

class A():
pass

class B():
pass

class C(A,B):
pass

a) Multi-level inheritance
b) Multiple inheritance
c) Hierarchical inheritance
d) Single-level inheritance

 

Python OOP

 

Which of the following is not a class method ??

a) Non-static
b) Static
c) Bounded
d) Unbounded

 

What will be the output of the following ??

class A:
def one(self):
return self.two()

def two(self):
return ‘A’

class B(A):
def two(self):
return ‘B’
obj1=A()
obj2=B()
print(obj1.two(),obj2.two())

 

a) A A
b) A B
c) B B
d) An exception is thrown

 

The assignment of more than one function to a particular operator is ??

a) Operator over-assignment
b) Operator overriding
c) Operator overloading
d) Operator instance

 

Object Oriented Programming Python: OOP MCQs Python

Object Oriented Programming Python. Multiple Choice Questions related to OOP concepts in Python Programming.

Object Oriented Programming Python

 

What does print(Test.__name__) display (assuming Test is the name of the class) ??

a) ()
b) Exception is thrown
c) Test
d) __main__

 

What will be the output of the following Python code ??

class Demo:
def __init__(self):
pass

def test(self):
print(__name__)

obj = Demo()
obj.test()

a) Exception is thrown
b) __main__
c) Demo
d) test

 

What will be the output of the ??

class stud:
‘Base class for all students’
def __init__(self, roll_no, grade):
self.roll_no = roll_no
self.grade = grade
def display (self):
print(“Roll no : “, self.roll_no, “, Grade: “, self.grade)
print(student.__doc__)

 

a) Exception is thrown
b) __main__
c) Nothing is displayed
d) Base class for all students

 

What will be the output of ??

def __init__(self, price):
self.price = price
obj=fruits(50)

obj.quantity=10
obj.bags=2

print(obj.quantity+len(obj.__dict__))

 

a) 12
b) 52
c) 13
d) 60

Object Oriented Programming Python

 

__del__ method is used to destroy instances of a class ??

a) True
b) False

 

What is Instantiation in terms of OOP terminology ??

a) Deleting an instance of class
b) Modifying an instance of class
c) Copying an instance of class
d) Creating an instance of class

 

What is delattr(obj,name) used for ??

a) To print deleted attribute
b) To delete an attribute
c) To check if an attribute is deleted or not
d) To set an attribute

 

What will be the output ??

class test:
def __init__(self):
self.variable = ‘Old’
self.Change(self.variable)
def Change(self, var):
var = ‘New’
obj=test()
print(obj.variable)

a) Error because function change can’t be called in the __init__ function
b) ‘New’ is printed
c) ‘Old’ is printed
d) Nothing is printed

 

Object Oriented Programming Python

 

What will be the output of the following code ??

class stud:
def __init__(self, roll_no, grade):
self.roll_no = roll_no
self.grade = grade
def display (self):
print(“Roll no : “, self.roll_no, “, Grade: “, self.grade)
stud1 = stud(34, ‘S’)
stud1.age=7
print(hasattr(stud1, ‘age’))

 

a) Error as age isn’t defined
b) True
c) False
d) 7

 

Is the following Python code correct ??

>>> class A:
def __init__(self,b):
self.b=b
def display(self):
print(self.b)
>>> obj=A(“Hello”)
>>> del obj

a) True
b) False

 

What is hasattr(obj,name) used for ??

a) To access the attribute of the object
b) To delete an attribute
c) To check if an attribute exists or not
d) To set an attribute

 

Object Oriented Programming Python

 

What will be the output of code ??

class test:
def __init__(self,a):
self.a=a

def display(self):
print(self.a)
obj=test()
obj.display()

 

a) Runs normally, doesn’t display anything
b) Displays 0, which is the automatic default value
c) Error as one argument is required while creating the object
d) Error as display function requires additional argument

 

What will be the output of following ??

>>> class demo():
def __repr__(self):
return ‘__repr__ built-in function called’
def __str__(self):
return ‘__str__ built-in function called’
>>> s=demo()
>>> print(s)

 

a) __str__ called
b) __repr__ called
c) Error
d) Nothing is printed

 

What will be the output of the following Python code ??

class change:
def __init__(self, x, y, z):
self.a = x + y + z

x = change(1,2,3)
y = getattr(x, ‘a’)
setattr(x, ‘a’, y+1)
print(x.a)

a) 6
b) 7
c) Error
d) 0

Python Try Except: Exception Handling MCQs Python

Python Try Except. MCQs on Exception Handling in Python. Try, Except, Finally, and other blocks and their usage with Examples. This section has 20+ Python Try Except Multiple Choice Questions.

Python Try Except

 

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

 

What will be the output of the following Python code ??

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

 

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

 

Identify the type of error in the following Python codes ??

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

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

 

 

Python Try Except

 

 

What will be the output of the following Python code ??

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

 

Is the following Python 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

 

What will be the output of the following Python code 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)

 

What will be the output of the following ??

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

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

 

Python Try Except

 

 

Is the following Python 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

 

What will be the output ??

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”)

 

What will be the output of the ??

x=10
y=8
assert x>y, ‘X too small’

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

 

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

 

 

Python Try Except

 

 

Compare the following two Python codes 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

 

The following Python code will result in an error if the input value is entered as 5 ??

assert False, ‘Spanish’

a) True
b) False

 

How many except statements can a try-except block have ??

a) zero
b) one
c) more than one
d) more than zero

 

What will be the output of the ??

int(‘65.43’)

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

 

What will be the output of the following Python code if the time module has already been imported ??

4 + ‘3’

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

 

What will be the output of the code ??

t[5]

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

 

What will be the output of the following Python ??

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

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

 

What happens if the file is not found in the following Python code ??

a=False
while not a:
try:
f_n = input(“Enter file name”)
i_f = open(f_n, ‘r’)
except:
print(“Input file not found”)

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

Exception Handling In Python: MCQs Exception Handling

Exception Handling In Python. MCQs on Exception Handling in Python Programming.

Exception Handling In Python

 

 

Which of the following blocks will be executed whether an exception is thrown or not ??

a) except
b) else
c) finally
d) assert

 

What will be the output of the following Python code ??

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

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

 

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

 

What exceptions are raised as a result of an error in opening a particular file ??

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

 

Exception Handling In Python

 

Which of the following is not an exception handling keyword in Python ??

a) try
b) except
c) accept
d) finally

 

What will be the output of the following Python code ??

try:
if ‘1’ != 1:
raise “someError”
else:
print(“someError has not occurred”)
except “someError”:
print (“someError has occurred”)

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

 

An exception is ??

a) an object
b) a special function
c) a standard module
d) a module

 

The error displayed in the following Python code 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

 

 

Exception Handling In Python

 

 

Syntax errors are also known as parsing errors ??

a) True
b) False

 

What will be the output of the following code ??

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]

 

What will be the output of the following Python code ??

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

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

 

Which of the following is not a standard exception in Python ??

a) NameError
b) IOError
c) AssignmentError
d) ValueError

 

Exception Handling In Python

 

 

What will be the output of the following ??

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

 

What will be the output of the following Python 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

 

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

 

Operator Overloading In Python: MCQs Python Programming

Operator Overloading In Python. Multiple Choice Questions on the topic of Operator Overloading in Python Programming. This set contains 10 Multiple Choice Questions.

 

Operator Overloading In Python

 

 

Which function overloads the // operator ??

a) __div__()
b) __ceildiv__()
c) __floordiv__()
d) __truediv__()

 

Which operator is overloaded by the __or__() function ??

a) ||
b) |
c) //
d) /

 

Let A and B be objects of class Foo. Which functions are called when print(A + B) is executed ??

a) __add__(), __str__()
b) __str__(), __add__()
c) __sum__(), __str__()
d) __str__(), __sum__()

 

Which function overloads the >> operator ??

a) __more__()
b) __gt__()
c) __ge__()
d) none of the mentioned

 

Which operator is overloaded by __lg__() ??

a) <
b) >
c) !=
d) none of the mentioned

 

 

Operator Overloading In Python

 

 

Which function overloads the == operator ??

a) __eq__()
b) __equ__()
c) __isequal__()
d) none of the mentioned

 

Which operator is overloaded by __invert__() ??

a) !
b) ~
c) ^
d) –

 

Which function overloads the + operator ??

a) __add__()
b) __plus__()
c) __sum__()
d) none of the mentioned

 

Which of the following Python code will print True ??

a = foo(2)
b = foo(3)
print(a < b)

 

a) class foo:
def __init__(self, x):
self.x = x
def __lt__(self, other):
if self.x < other.x:
return False
else:
return True

 

b) class foo:
def __init__(self, x):
self.x = x
def __less__(self, other):
if self.x > other.x:
return False
else:
return True

 

c) class foo:
def __init__(self, x):
self.x = x
def __lt__(self, other):
if self.x < other.x:
return True
else:
return False

 

d) class foo:
def __init__(self, x):
self.x = x
def __less__(self, other):
if self.x < other.x:
return False
else:
return True

 

Which function is called when the following Python code is executed ??

f = foo()
format(f)

a) format()
b) __format__()
c) str()
d) __str__()

Python Files Interview Questions: Files in Python language

Python Files Interview Questions. Multiple Choice Questions And Answers on Files in Python programming.

 

Python Files Interview Questions

 

 

What happens if no arguments are passed to the seek function ??

a) file position is set to the start of file
b) file position is set to the end of file
c) file position remains unchanged
d) error

 

Which of the following are the modes of both writing and reading in binary format in file ??

a) wb+
b) w
c) wb
d) w+

 

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

 

Is it possible to create a text file in python ??

a) Yes
b) No
c) Machine dependent
d) All of the mentioned

 

How do you delete a file ??

a) del(fp)
b) fp.delete()
c) os.remove(‘file’)
d) os.delete(‘file’)

 

Which function is used to close a file in python ??

a) Close()
b) Stop()
c) End()
d) Closefile()

 

How do you rename a file ??

a) fp.name = ‘new_name.txt’
b) os.rename(existing_name, new_name)
c) os.rename(fp, new_name)
d) os.set_name(existing_name, new_name)

 

Which function is used to write a list of string in a file ??

a) writeline()
b) writelines()
c) writestatement()
d) writefullline()

 

How do you get the current position within the file ??

a) fp.seek()
b) fp.tell()
c) fp.loc
d) fp.pos

 

Which function is used to write all the characters ??

a) write()
b) writecharacters()
c) writeall()
d) writechar()

 

How do you close a file object (fp) ??

a) close(fp)
b) fclose(fp)
c) fp.close()
d) fp.__close__()

 

Which function is used to read single line from file ??

a) Readline()
b) Readlines()
c) Readstatement()
d) Readfullline()

 

Which of the following is not a valid attribute of a file object (fp) ??

a) fp.name
b) fp.closed
c) fp.mode
d) fp.size

 

Which function is used to read all the characters ??

a) Read()
b) Readcharacters()
c) Readall()
d) Readchar()

 

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__()

 

What is the use of “a” in file handling ??

a) Read
b) Write
c) Append
d) None of the mentioned

 

What is the difference between r+ and w+ modes ??

a) no difference
b) in r+ the pointer is initially placed at the beginning of the file and the pointer is at the end for w+
c) in w+ the pointer is initially placed at the beginning of the file and the pointer is at the end for r+
d) depends on the operating system

 

What is the use of “w” in file handling ??

a) Read
b) Write
c) Append
d) None of the mentioned

 

Which of the following is not a valid mode to open a file ??

a) ab
b) rw
c) r+
d) w+

 

In file handling, what does this terms means “r, a” ??

a) read, append
b) append, read
c) write, append
d) none of the mentioned

 

error: Content is protected !!