Exercise: Tricky Questions
Questions for: Tricky Questions
What is the output of the following Python code?
x = [1, 2, 3, 4, 5]
result = x[-2:-1]
print(result)
A:
[4]
B:
[5]
C:
[3, 4]
D:
[4, 5]
Answer: A
Slicing with indices -2:-1 returns a list containing the element at index -2 (counting from the end).
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:
20
C:
This code will result in an error.
D:
10
Answer: A
The child class
Child initializes both x and y, and the result is the sum of these attributes.Discuss About this Question.
What is the output of the following Python code?
def func(x, y=[]):
y.append(x)
return y
result1 = func(1)
result2 = func(2)
print(result1 + result2)
A:
[1, 2]
B:
[1, 2, 1, 2]
C:
[1, 2, 2]
D:
[1, 2, 1, 2, 2]
Answer: B
The code defines a function called
Inside the
In the code,
Similarly,
When
Finally,
func that takes two parameters: x and y. The default value for y is an empty list [].
Inside the
func function, the value of x is appended to the list y using the append() method. Then, the modified y list is returned.
In the code,
result1 is assigned the result of calling func(1). Since y is not provided as an argument, it uses the default value of []. Therefore, result1 is [1].
Similarly,
result2 is assigned the result of calling func(2). Again, y is not provided as an argument, so it uses the default value of []. However, since the default value is a mutable object (a list), it retains its state from previous function calls. Therefore, result2 is [1, 2].
When
result1 + result2 is evaluated, it concatenates the two lists, resulting in [1, 2, 1, 2].
Finally,
[1, 2, 1, 2] is printed to the console as the output of the code.Discuss About this Question.
Consider the following Python code:
class CustomClass:
def __init__(self, value):
self.__value = value
def get_value(self):
return self.__value
obj = CustomClass(42)
result = obj.get_value()
print(result)
What will be the value of result?
A:
42
B:
This code will result in an error.
C:
0
D:
None
Answer: A
The private attribute
__value is accessed through the public method get_value.Discuss About this Question.
What will be the output of the following Python code?
def func(x):
x += 1
return x
x = 5
result = func(x)
print(x, result)
A:
5 6
B:
6 6
C:
5 5
D:
This code will result in an error.
Answer: A
The function modifies its local copy of
x, and the global x remains unchanged.Discuss About this Question.
Ad Slot (Above Pagination)
Discuss About this Question.