PCEP-30-02 · Question #173
What is the output of the following snippet? ``python def fun(x): x += 1 return x x = 2 x = fun(x + 1) print(x) ``
The correct answer is A. 4. Option A (4) is correct because Python evaluates x + 1 first (2 + 1 = 3) before passing it to fun, then fun adds 1 more (3 + 1 = 4) and returns that value, which overwrites x. B (5) is wrong - this would only be correct if x were incremented twice from its base value of 2 plus…
Question
def fun(x):
x += 1
return x
x = 2
x = fun(x + 1)
print(x)
Options
- A4
- B5
- CThe code is erroneous.
- D3
How the community answered
(48 responses)- A79% (38)
- B2% (1)
- C13% (6)
- D6% (3)
Explanation
Option A (4) is correct because Python evaluates x + 1 first (2 + 1 = 3) before passing it to fun, then fun adds 1 more (3 + 1 = 4) and returns that value, which overwrites x.
B (5) is wrong - this would only be correct if x were incremented twice from its base value of 2 plus 2 extra, which misreads the call as fun(x) + 1 or double-counts the addition.
D (3) is wrong - this mistakes fun(x + 1) for fun(x), missing that the argument passed in is already 3, not 2.
C is wrong - the code runs without errors; Python has no issue with reusing the variable name x inside the function, since the inner x is a local copy.
Memory tip: Always evaluate the argument expression first, then the function body - think of it as two separate "+1" steps happening in sequence: one before the call, one inside it.
Community Discussion
No community discussion yet for this question.