nerdexam
Python_Institute

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

What is the expected behavior of the following snippet?
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)
  • A
    9% (5)
  • B
    4% (2)
  • C
    2% (1)
  • D
    2% (1)
  • E
    84% (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 literal 2, you'd think x = 2, giving a(2) = 4. The mistake is forgetting to evaluate a(x) before assigning.
  • C (print 6): Likely comes from assuming x remains 1 throughout, then computing a(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 a is 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.

Full PCEP-30-02 Practice