nerdexam
Python_Institute

PCEP-30-02 · Question #170

What is the expected output of the following code? ``python num = 1 def func(): num = num + 3 print(num) func() print(num) ``

The correct answer is D. The code is erroneous. Option D is correct because Python raises an UnboundLocalError when func() is called. The moment Python sees num = num + 3 inside the function, it classifies num as a local variable for the entire function scope - but then the right-hand side num + 3 tries to read that local…

Question

What is the expected output of the following code?
num = 1

def func():
 num = num + 3
 print(num)

func()
print(num)

Options

  • A41
  • B44
  • C14
  • DThe code is erroneous.
  • E11

How the community answered

(30 responses)
  • A
    3% (1)
  • B
    7% (2)
  • C
    10% (3)
  • D
    77% (23)
  • E
    3% (1)

Explanation

Option D is correct because Python raises an UnboundLocalError when func() is called. The moment Python sees num = num + 3 inside the function, it classifies num as a local variable for the entire function scope - but then the right-hand side num + 3 tries to read that local num before it has been assigned, crashing with UnboundLocalError: local variable 'num' referenced before assignment.

Options A, B, C, and E are all wrong for the same reason: they assume the code runs to completion, which it never does. No arithmetic happens, so no printed output is produced at all. To actually modify the global num inside func, you would need to declare global num at the top of the function.

Memory tip: Think of it as "assignment claims the name." The instant Python sees any assignment to a name inside a function body, it claims that name as local for the whole function - even lines above the assignment - so reading it beforehand is always an error.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice