Python Programming - Tricky Questions

Exercise : Tricky Questions - General Questions
  • Tricky Questions - General Questions
1.
What is the output of the following Python code?
def mystery_function(x):
    return x if x > 0 else mystery_function(-x)

result = mystery_function(-5)
print(result)
-5
5
0
This code will result in an infinite loop.
Answer: Option
Explanation:
The mystery_function recursively calls itself with the absolute value of the input until the input is greater than 0. Therefore, mystery_function(-5) returns mystery_function(5), resulting in the output 5.

2.
What is the value of result after executing the following Python code?
my_list = [1, 2, 3, 4, 5]
result = my_list[::2]
[1, 3, 5]
[2, 4]
[5, 3, 1]
[1, 2, 3, 4, 5]
Answer: Option
Explanation:
The slicing notation my_list[::2] extracts elements with a step of 2, starting from index 0. Therefore, it includes elements at indices 0, 2, and 4, resulting in the list [1, 3, 5].

3.
What will be the output of the following Python code?
x = 5
y = 2

result = x // y
2.5
2
3
2.0
Answer: Option
Explanation:
The // operator performs integer division in Python, discarding any remainder. Therefore, 5 // 2 results in 2.

4.
What is the correct way to check if a key is present in a dictionary?
my_dict = {'name': 'John', 'age': 25}
key_to_check = 'age'
if key_to_check in my_dict.keys():
if key_to_check in my_dict:
if my_dict.contains(key_to_check):
if my_dict.exists(key_to_check):
Answer: Option
Explanation:
The correct way to check if a key is present in a dictionary is to use the in keyword directly on the dictionary.

5.
What will be the output of the following Python code?
x = [1, 2, 3]
y = x
y[0] = 10
print(x)
[10, 2, 3]
[1, 2, 3]
[10, 2, 3] (but with a warning)
[1, 2, 3] (but with a warning)
Answer: Option
Explanation:
Both x and y reference the same list object. Therefore, modifying y also modifies x, resulting in the output [10, 2, 3].