PCEP-30-02 · Question #212
``python def any(): var = 1 print(var + 1, end='') var = 1 any() print(var) `` What is the output of the following snippet?
The correct answer is B. 21. Option B (21) is correct because Python treats var inside any() as a local variable - it shadows the global var but never modifies it. The function prints var + 1 → 1 + 1 = 2 with end='' (no newline), then print(var) outside the function reads the unchanged global var = 1 and…
Question
def any():
var = 1
print(var + 1, end='')
var = 1
any()
print(var)
What is the output of the following snippet?Options
- A22
- B21
- C12
- D11
How the community answered
(29 responses)- A3% (1)
- B76% (22)
- C14% (4)
- D7% (2)
Explanation
Option B (21) is correct because Python treats var inside any() as a local variable - it shadows the global var but never modifies it. The function prints var + 1 → 1 + 1 = 2 with end='' (no newline), then print(var) outside the function reads the unchanged global var = 1 and prints 1 with a newline, yielding 21.
- A (22) is wrong because the global
varis never reassigned; it remains1, not2. - C (12) is wrong because execution order matters - the function call happens first, printing
2, then the global print adds1. - D (11) is wrong because
var + 1evaluates to2, not1; addition is performed, not ignored.
Memory tip: Think "local = locked in." A variable assigned inside a function stays inside that function - it can't reach out to change the global, and its changes die when the function returns. If you don't see the global keyword, assume the function's copy is its own.
Community Discussion
No community discussion yet for this question.