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)- B15% (3)
- C5% (1)
- D5% (1)
- E75% (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 globalnumto 3 - it doesn't; withoutglobal num, it's a new local variable. - B (11): Assumes the local
num = 3is ignored and the function reads the global1instead - Python reads the local assignment first. - C (erroneous): The code runs cleanly; no
UnboundLocalErroroccurs becausenumis assigned before it's read insidefunc(). - D (13): Reverses the call order -
func()executes before the outerprint(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.