PCEP-30-02 · Question #175
What is the expected behavior of the following snippet? ``python x = 1 def a(x): return 2 * x x = 2 + a(x) # Line 8 print(a(x)) # Line 9 ``
The correct answer is E. print 8. Option E is correct because Python evaluates Line 8 as x = 2 + a(1) - since x is 1 at that point, a(1) returns 2, making x = 4. Line 9 then calls a(4), which returns 2 4 = 8. Why the distractors are wrong: D (print 4): A common trap - if you ignore the a(x) call on Line 8 and…
Question
x = 1
def a(x):
return 2 * x
x = 2 + a(x) # Line 8
print(a(x)) # Line 9
Options
- Acause a runtime exception on Line 9
- Bcause a runtime exception on Line 8
- Cprint 6
- Dprint 4
- Eprint 8
How the community answered
(55 responses)- A9% (5)
- B4% (2)
- C2% (1)
- D2% (1)
- E84% (46)
Explanation
Option E is correct because Python evaluates Line 8 as x = 2 + a(1) - since x is 1 at that point, a(1) returns 2, making x = 4. Line 9 then calls a(4), which returns 2 * 4 = 8.
Why the distractors are wrong:
- D (print 4): A common trap - if you ignore the
a(x)call on Line 8 and only see the literal2, you'd thinkx = 2, givinga(2) = 4. The mistake is forgetting to evaluatea(x)before assigning. - C (print 6): Likely comes from assuming
xremains1throughout, then computinga(1) + a(1) = 4... or other wrong arithmetic - there's no path to 6 in correct execution. - B and A (runtime exceptions): No exception occurs at either line - the function
ais defined before it's called, and integers are valid arguments. Python has no issue with any of this code.
Memory tip: When you see x = expr_with_x on the right side, Python fully evaluates the right side first using the current value of x before assigning the result back - so always trace variable values step-by-step from top to bottom rather than reading left-to-right across the assignment.
Community Discussion
No community discussion yet for this question.