PCEP-30-02 · Question #187
What is the expected output of the following code? x = 42 def func(): global x print('1. x:', x) x = 23 print('2. x:', x) func() print('3. x:', x)
The correct answer is C. 1. x: 42 2. x: 23 3. x: 23. Option C is correct because the global x declaration inside func() tells Python to use the same x that lives in the module's global scope - not a local copy. When func() runs, it first reads the global x (still 42), prints it, then reassigns it to 23, which modifies the global…
Question
Options
- A
- x: 42
- x: 42
- x: 42
- BNone of the above.
- C
- x: 42
- x: 23
- x: 23
- D
- x: 42
- x: 23
- x: 42
How the community answered
(41 responses)- A5% (2)
- B2% (1)
- C80% (33)
- D12% (5)
Explanation
Option C is correct because the global x declaration inside func() tells Python to use the same x that lives in the module's global scope - not a local copy. When func() runs, it first reads the global x (still 42), prints it, then reassigns it to 23, which modifies the global variable in place. After func() returns, print('3. x:', x) sees the updated global value of 23, not the original 42.
Why the distractors fail:
- A is wrong because it assumes
x = 23inside the function has no effect, which would only be true ifglobal xwere absent (in which case Python would raise anUnboundLocalErrorbefore even printing line 1, since it sees a local assignment). - D is wrong because it assumes the global reassignment doesn't persist after the function exits - but
global xmeans the change is permanent. - B is wrong because C is a valid, well-defined output.
Memory tip: Think of global as "don't make a new local copy - reach out and grab the real one." Without it, any assignment inside a function creates a local variable; with it, the assignment writes directly to the outer scope, and that change outlives the function call.
Community Discussion
No community discussion yet for this question.