nerdexam
Python_Institute

PCEP-30-02 · Question #205

``python num = 1 def func(): num = 3 print(num, end=' ') func() print(num) `` What is the output of the following snippet?

The correct answer is E. 31. Option E (3 1) is correct because Python's scoping rules treat num = 3 inside func() as a local variable - it shadows the global num without modifying it. So func() prints 3, and the subsequent print(num) sees the original global value, printing 1. Why the distractors fail: A…

Question

num = 1

def func():
 num = 3
 print(num, end=' ')

func()

print(num)
What is the output of the following snippet?

Options

  • A33
  • B11
  • CThe code is erroneous.
  • D13
  • E31

How the community answered

(20 responses)
  • B
    15% (3)
  • C
    5% (1)
  • D
    5% (1)
  • E
    75% (15)

Explanation

Option E (3 1) is correct because Python's scoping rules treat num = 3 inside func() as a local variable - it shadows the global num without modifying it. So func() prints 3, and the subsequent print(num) sees the original global value, printing 1.

Why the distractors fail:

  • A (33): Assumes the assignment inside func() changes the global num to 3 - it doesn't; without global num, it's a new local variable.
  • B (11): Assumes the local num = 3 is ignored and the function reads the global 1 instead - Python reads the local assignment first.
  • C (erroneous): The code runs cleanly; no UnboundLocalError occurs because num is assigned before it's read inside func().
  • D (13): Reverses the call order - func() executes before the outer print(num), so it must be 3 first, then 1.

Memory tip: Think "LEGB" - Python looks up names Local → Enclosing → Global → Built-in. A bare assignment inside a function always creates a Local variable, leaving the Global untouched unless you explicitly declare global num.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice