Exercise: Tricky Questions

Questions for: Tricky Questions

What is the output of the following Python code?
my_list = [1, 2, 3, 4]
result = [x if x % 2 == 0 else -x for x in my_list]
print(result)
A:
[1, -2, 3, -4]
B:
[-1, 2, -3, 4]
C:
[1, -2, -3, -4]
D:
[1, -2, 3, 4]
Answer: B
List comprehension is used to create a new list where even numbers are unchanged, and odd numbers are negated.
What will be the output of the following Python code?
def power(x, n=2):
    return x ** n

result1 = power(2)
result2 = power(2, 3)

print(result1 + result2)
A:
10
B:
16
C:
12
D:
64
Answer: C

The code defines a function called power that calculates the power of a number using the ** operator. In the code, result1 is the result of calling power(2), which calculates 2 raised to the power of 2, resulting in 4.

Similarly, result2 is the result of calling power(2, 3), which calculates 2 raised to the power of 3, resulting in 8. The expression result1 + result2 calculates the sum of result1 and result2, resulting in 4 + 8 = 12.

Finally, 12 is printed to the console as the output of the code.

What is the output of the following Python code?
def mysterious_function(a, b=[]):
    b.append(a)
    return b

result1 = mysterious_function(1)
result2 = mysterious_function(2)
result3 = mysterious_function(3)

print(result1 + result2 + result3)
A:
[1, 2, 3, 1, 2, 3, 1, 2, 3]
B:
[1, 2, 3]
C:
[1, 2, 3, 3, 3, 3, 3, 3, 3]
D:
This code will result in an error.
Answer: A
The mysterious_function appends the value of a to the list b and returns b. In the code, result1 is [1], result2 is [1, 2], and result3 is [1, 2, 3]. When print(result1 + result2 + result3) is executed, it concatenates the three lists, resulting in [1, 2, 3, 1, 2, 3, 1, 2, 3]. Therefore, the output of the code is [1, 2, 3, 1, 2, 3, 1, 2, 3].
What will be the output of the following Python code?
def outer_function(x):
    def inner_function():
        return x + 1
    return inner_function

closure = outer_function(5)
result = closure()
print(result)
A:
5
B:
6
C:
11
D:
This code will result in an error.
Answer: B
The inner_function is a closure that "remembers" the value of x from its enclosing scope. When closure() is called, it returns 5 + 1, resulting in the output 6.
What will be the output of the following Python code?
x = [1, 2, 3]
y = x
y[0] = 10
print(x)
A:
[10, 2, 3]
B:
[1, 2, 3]
C:
[10, 2, 3] (but with a warning)
D:
[1, 2, 3] (but with a warning)
Answer: A
Both x and y reference the same list object. Therefore, modifying y also modifies x, resulting in the output [10, 2, 3].
Ad Slot (Above Pagination)
Quiz