Python Programming - Tricky Questions

Exercise : Tricky Questions - General Questions
  • Tricky Questions - General Questions
36.
What is the output of the following Python code?
x = 5
y = x if x > 10 else x/2
print(y)
5
2.5
10
This code will result in an error.
Answer: Option
Explanation:
The ternary conditional expression sets y to x if x > 10, otherwise it sets y to x/2.

37.
What is the output of the following Python code?
x = [1, 2, 3]
y = x[:]
y[0] = 10
print(x)
[1, 2, 3]
[10, 2, 3]
[10, 2, 3] (but with a warning)
[1, 2, 3, 10]
Answer: Option
Explanation:
Slicing with [:] creates a new copy of the list, so modifying y does not affect x.

38.
What will be the output of the following Python code?
class MyClass:
    x = 10

obj = MyClass()
obj.x += 5
result = obj.x
print(result)
10
5
15
This code will result in an error.
Answer: Option
Explanation:
The attribute x is incremented by 5 using the instance obj.

39.
What is the output of the following Python code?
x = 2
y = 3
result = x * y ** x
print(result)
12
18
24
8
Answer: Option
Explanation:
Exponentiation (**), performed before multiplication, results in 3 ** 2, and then multiplied by 2.

40.
Consider the following Python code:
def my_decorator(func):
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        return result * 2
    return wrapper

@my_decorator
def my_function(x):
    return x + 1

result = my_function(5)
print(result)
What will be the value of result?
6
10
12
This code will result in an error.
Answer: Option
Explanation:
The decorator multiplies the result of the function by 2.