Python Programming - Tricky Questions

Exercise : Tricky Questions - General Questions
  • Tricky Questions - General Questions
26.
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?
42
This code will result in an error.
0
None
Answer: Option
Explanation:
The private attribute __value is accessed through the public method get_value.

27.
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)
[1, 2]
[1, 2, 1, 2]
[1, 2, 2]
[1, 2, 1, 2, 2]
Answer: Option
Explanation:
The code defines a function called 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.

28.
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)
30
20
This code will result in an error.
10
Answer: Option
Explanation:
The child class Child initializes both x and y, and the result is the sum of these attributes.

29.
What is the output of the following Python code?
x = [1, 2, 3, 4, 5]
result = x[-2:-1]
print(result)
[4]
[5]
[3, 4]
[4, 5]
Answer: Option
Explanation:
Slicing with indices -2:-1 returns a list containing the element at index -2 (counting from the end).

30.
Consider the following Python code:
def my_generator():
    yield 1
    yield 2
    yield 3

result = list(my_generator())
print(result)
What will be the output of this code?
[1, 2, 3]
(1, 2, 3)
{1, 2, 3}
This code will result in an error.
Answer: Option
Explanation:
The generator function is converted to a list using the list() constructor.