Exercise: Tricky Questions

Questions for: Tricky Questions

What will be the output of the following Python code?
class MyClass:
    x = 10

obj1 = MyClass()
obj2 = MyClass()
obj1.x += 5
result = obj2.x
print(result)
A:
10
B:
5
C:
15
D:
This code will result in an error.
Answer: A
The code defines a class called MyClass with a class variable x set to 10.
obj1 and obj2 are both instances of the MyClass class.
When obj1.x += 5 is executed, it modifies the x attribute of obj1 by adding 5 to its current value. Since obj1 does not have its own x attribute, it accesses the class variable x and performs the addition. As a result, obj1.x becomes 15.
When result = obj2.x is executed, it assigns the value of obj2.x to the variable result. Since obj2 does not have its own x attribute, it also accesses the class variable x. Therefore, result is 10.
Finally, 10 is printed to the console as the output of the code.
What is the output of the following Python code?
x = [1, 2, 3]
y = x
x += [4, 5]
print(y)
A:
[1, 2, 3]
B:
[1, 2, 3, 4, 5]
C:
[1, 2, 3, 4, 5] (but with a warning)
D:
This code will result in an error.
Answer: B
The += operator modifies the list in-place, and y reflects this change.
Consider the following Python code:
def my_generator():
    for i in range(5):
        yield i * 2

result = list(my_generator())
print(result)
What will be the output of this code?
A:
[0, 2, 4, 6, 8]
B:
[0, 1, 4, 9, 16]
C:
[0, 2, 4, 8, 16]
D:
This code will result in an error.
Answer: A
The generator yields values multiplied by 2 in the range [0, 2, 4, 6, 8].
What will be the output of the following Python code?
class Parent:
    def __init__(self, x):
        self.x = x

class Child(Parent):
    def __init__(self, x, y):
        super().__init__(x)
        self.y = y

obj = Child(10, 20)
result = obj.x * obj.y
print(result)
A:
30
B:
200
C:
This code will result in an error.
D:
10
Answer: B
The child class Child initializes x and y, and the result is the product of these attributes.
What is the output of the following Python code?
a = [1, 2, 3]
b = a
a = a + [4, 5]
print(b)
A:
[1, 2, 3]
B:
[1, 2, 3, 4, 5]
C:
This code will result in an error.
D:
[1, 2, 3, 4, 5] (but with a warning)
Answer: A
The concatenation creates a new list, and b still refers to the original list.
Ad Slot (Above Pagination)
Quiz