What will be the output of the following code?
class Counter:
count = 0
def __init__(self):
Counter.count += 1
a = Counter()
b = Counter()
c = Counter()
print(Counter.count)
Answer: C
count is a class variable shared across all instances. Each time __init__ is called (once per object creation), Counter.count is incremented by 1. Since three objects (a, b, c) are created, Counter.count becomes 3.
Q.122Medium
What will be the output of the following code?
class MyClass:
def __init__(self, x):
self.__x = x
obj = MyClass(10)
print(obj.__x)
Answer: C
__x is a name-mangled private attribute. Python internally renames it to _MyClass__x to prevent direct external access. Accessing obj.__x from outside the class raises an AttributeError. The correct way to access it would be obj._MyClass__x.
Q.123Medium
Which of the following correctly defines a class method in Python?
Answer: C
A class method is defined using the @classmethod decorator and takes cls as its first argument, which refers to the class itself rather than an instance. Option A is an instance method, Option B is a static method (with wrong usage), and Option D uses @classmethod but incorrectly names the first parameter self instead of cls (though it would still work, cls is the convention and expected answer).
Q.124Medium
What is the output of the following code?
class Shape:
def area(self):
return 0
class Circle(Shape):
def __init__(self, r):
self.r = r
def area(self):
return 3.14 * self.r * self.r
shapes = [Shape(), Circle(7)]
for s in shapes:
print(s.area())
Answer: B
This demonstrates polymorphism. The list contains a Shape and a Circle. When area() is called on the Shape instance, it returns 0. When called on the Circle instance with r=7, it returns 3.14 * 7 * 7 = 153.86. Python dynamically resolves the correct method for each object.
Q.125Medium
What will be the output of the following code?
class A:
def greet(self):
return 'Hello from A'
class B(A):
def greet(self):
return super().greet() + ' and B'
obj = B()
print(obj.greet())
Answer: B
super().greet() in class B calls the greet() method of the parent class A, which returns 'Hello from A'. The string ' and B' is concatenated to it. So the final output is 'Hello from A and B'. The super() function is used to call methods from the parent class.
Advertisement
Q.126Medium
What will be the output of the following code?
class Vehicle:
def __init__(self, brand):
self.brand = brand
class Car(Vehicle):
def __init__(self, brand, model):
super().__init__(brand)
self.model = model
c = Car('Toyota', 'Camry')
print(c.brand, c.model)
Answer: A
Car's __init__ calls super().__init__(brand), which invokes Vehicle's __init__ and sets self.brand = 'Toyota'. Then self.model = 'Camry' is set in Car's __init__. So c.brand is 'Toyota' and c.model is 'Camry', printing 'Toyota Camry'.
Q.127Medium
What is the output of the following code?
class Box:
def __init__(self, vol):
self.vol = vol
def __gt__(self, other):
return self.vol > other.vol
b1 = Box(10)
b2 = Box(20)
print(b1 > b2)
Answer: B
The __gt__ method is a dunder method that overloads the > operator. When b1 > b2 is evaluated, Python calls b1.__gt__(b2), which returns self.vol > other.vol, i.e., 10 > 20, which is False. This is an example of operator overloading in Python.
Q.128Medium
What will be the output of the following code?
class Foo:
def __init__(self):
self.x = 10
def bar(self):
self.x += 5
return self.x
obj1 = Foo()
obj2 = Foo()
obj1.bar()
print(obj1.x, obj2.x)
Answer: C
Each instance of Foo has its own copy of self.x initialized to 10. Calling obj1.bar() modifies only obj1.x by adding 5, making it 15. obj2 is a separate instance and its x remains 10. So the output is '15 10', demonstrating instance variable independence.
Q.129Medium
Which of the following modes opens a file for both reading and writing without truncating the file, and raises an error if the file does not exist?
Answer: B
The mode 'r+' opens an existing file for both reading and writing. It raises FileNotFoundError if the file does not exist and does not truncate the file. 'w+' truncates the file (or creates it), 'a+' always appends, and 'x+' creates a new file but fails if it already exists.
Q.130Medium
What will be the output of the following code?
with open('test.txt', 'w') as f:
f.write('Hello')
f.write(' World')
with open('test.txt', 'r') as f:
print(f.read())
Answer: B
The write() method does not add a newline automatically. Both write() calls append their strings directly, so the file contains 'Hello World'. When read back, it prints 'Hello World'.
Q.131Medium
Which method reads all lines of a file and returns them as a list of strings, with each string ending in a newline character?
Answer: C
readlines() reads the entire file and returns a list where each element is one line including the newline character '\n'. read() returns the entire content as a single string, readline() reads only one line at a time, and readall() is not a standard Python file method.
Q.132Medium
What does the seek(0) method do when called on an open file object?
Answer: B
seek(n) moves the file pointer to byte position n. seek(0) moves the pointer to the very beginning (byte 0) of the file, allowing subsequent reads to start from the beginning. tell() is used to return the current position, not seek().
Q.133Medium
What will be the output of the following code?
f = open('data.txt', 'w')
f.write('Line 1\nLine 2\nLine 3')
f.close()
f = open('data.txt', 'r')
print(len(f.readlines()))
f.close()
Answer: C
The string written contains two '\n' characters, splitting the content into three lines: 'Line 1\n', 'Line 2\n', and 'Line 3'. readlines() returns a list of these three lines, so len() returns 3.
Q.134Medium
Which of the following is the correct way to open a file in binary write mode in Python?
Answer: B
Binary mode is specified by appending 'b' after the primary mode character. 'wb' means write in binary mode. 'b' alone is not a valid mode, 'bw' is an invalid ordering, and 'binary' is not a recognized mode string in Python.
Q.135Medium
What is the advantage of using the 'with' statement when working with files in Python?
Answer: B
The 'with' statement uses a context manager that guarantees the file's __exit__ method is called, which closes the file automatically when the block ends — even if an exception is raised. This prevents resource leaks without requiring explicit f.close() calls.
Q.136Medium
What will the following code print?
with open('sample.txt', 'w') as f:
f.write('Python\nFile Handling')
with open('sample.txt', 'r') as f:
line = f.readline()
print(line.strip())
Answer: C
readline() reads only the first line up to and including the newline character, returning 'Python\n'. strip() removes the trailing newline, so the output is 'Python'. The second line 'File Handling' is never read.
Q.137Medium
What exception is raised when you try to open a file that does not exist using open('missing.txt', 'r')?
Answer: C
In Python 3, attempting to open a non-existent file in read mode raises FileNotFoundError, which is a subclass of OSError. While catching OSError would also work, the specific exception raised is FileNotFoundError. FileExistsError is raised when trying to create a file that already exists (mode 'x').
Q.138Medium
What will be the output of the following code?
with open('test.txt', 'w') as f:
f.write('Hello World')
with open('test.txt', 'a') as f:
f.write('!!!')
with open('test.txt', 'r') as f:
print(f.read())
Answer: C
The first block writes 'Hello World' to the file. The second block opens the file in append mode ('a'), which does not truncate the file but moves the pointer to the end, then appends '!!!'. Reading the file finally gives 'Hello World!!!'.
Q.139Medium
What will be the output of the following code?
def greet(name, msg='Hello'):
return f'{msg}, {name}!'
print(greet('Alice'))
print(greet('Bob', 'Hi'))
Answer: A
The function greet() has a default parameter msg='Hello'. When called as greet('Alice'), msg takes its default value 'Hello', producing 'Hello, Alice!'. When called as greet('Bob', 'Hi'), msg is overridden to 'Hi', producing 'Hi, Bob!'. So the output is:
Hello, Alice!
Hi, Bob!
Q.140Medium
What will be the output of the following code?
def func(*args, **kwargs):
print(len(args), len(kwargs))
func(1, 2, 3, a=4, b=5)
Answer: B
*args collects positional arguments into a tuple. Here, 1, 2, 3 are positional, so args = (1, 2, 3) and len(args) = 3. **kwargs collects keyword arguments into a dictionary. Here, a=4, b=5 are keyword arguments, so kwargs = {'a': 4, 'b': 5} and len(kwargs) = 2. The output is 3 2.