Exercise: Tricky Questions

Questions for: Tricky Questions

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?
A:
6
B:
10
C:
12
D:
This code will result in an error.
Answer: C
The decorator multiplies the result of the function by 2.
What is the output of the following Python code?
x = 2
y = 3
result = x * y ** x
print(result)
A:
12
B:
18
C:
24
D:
8
Answer: B
Exponentiation (**), performed before multiplication, results in 3 ** 2, and then multiplied by 2.
What will be the output of the following Python code?
class MyClass:
    x = 10

obj = MyClass()
obj.x += 5
result = obj.x
print(result)
A:
10
B:
5
C:
15
D:
This code will result in an error.
Answer: C
The attribute x is incremented by 5 using the instance obj.
What is the output of the following Python code?
x = [1, 2, 3]
y = x[:]
y[0] = 10
print(x)
A:
[1, 2, 3]
B:
[10, 2, 3]
C:
[10, 2, 3] (but with a warning)
D:
[1, 2, 3, 10]
Answer: A
Slicing with [:] creates a new copy of the list, so modifying y does not affect x.
What will be the output of the following Python code?
string1 = "Python"
string2 = string1
string2 += " is great"
result = string1 + string2
print(result)
A:
"Python is greatPython is great"
B:
"PythonPython is great"
C:
"Python is great is great"
D:
This code will result in an error.
Answer: B
Immutable strings, when concatenated, create a new string.
Ad Slot (Above Pagination)
Quiz