Python Programming - Tricky Questions
Exercise : Tricky Questions - General Questions
- Tricky Questions - General Questions
6.
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)
Answer: Option
Explanation:
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
.
7.
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)
Answer: Option
Explanation:
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]
.
8.
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)
Answer: Option
Explanation:
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.
9.
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)
Answer: Option
Explanation:
List comprehension is used to create a new list where even numbers are unchanged, and odd numbers are negated.
10.
Consider the following Python code:
class CustomError(Exception):
def __init__(self, message):
super().__init__(message)
raise CustomError("An example custom error.")
What will happen when this code is executed?
Answer: Option
Explanation:
The code raises a custom error of type
CustomError
with the specified message.
Quick links
Quantitative Aptitude
Verbal (English)
Reasoning
Programming
Interview
Placement Papers