PCEP-30-02 · Question #222
What is the expected output of the following code? ``python def func(): print(x + 1, end=' ') x = 1 func() print(x) ``
The correct answer is A. 21. Option A (2 1) is correct because Python's LEGB scoping rule lets func() read the global variable x=1 without needing a global declaration - it just can't modify it. So print(x + 1, end=' ') outputs 2 followed by a space (no newline), then print(x) outputs the unchanged global…
Question
def func():
print(x + 1, end=' ')
x = 1
func()
print(x)
Options
- A21
- B22
- C11
- D12
How the community answered
(27 responses)- A81% (22)
- B4% (1)
- C4% (1)
- D11% (3)
Explanation
Option A (2 1) is correct because Python's LEGB scoping rule lets func() read the global variable x=1 without needing a global declaration - it just can't modify it. So print(x + 1, end=' ') outputs 2 followed by a space (no newline), then print(x) outputs the unchanged global x=1 on the same line, giving 2 1.
Why the distractors fail:
- B (2 2): Would require
xto equal 2 when the secondprintruns, butfunc()never modifiesx- it only reads it. - C (1 1): Would require
x + 1to equal 1, implyingx=0, which contradicts the assignmentx = 1. - D (1 2): Would require the outputs to be swapped or
x+1to equal 1, neither of which is possible here.
Memory tip: The key rule to remember is read globally, write locally - a function can silently read a global variable, but any attempt to assign to it without global creates a new local variable instead (and would raise UnboundLocalError if read before assignment). Here, since func only reads x, no global keyword is needed and the global x stays at 1.
Community Discussion
No community discussion yet for this question.