nerdexam
Python_Institute

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)
  • A
    3% (1)
  • B
    76% (22)
  • C
    14% (4)
  • D
    7% (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 + 11 + 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 var is never reassigned; it remains 1, not 2.
  • C (12) is wrong because execution order matters - the function call happens first, printing 2, then the global print adds 1.
  • D (11) is wrong because var + 1 evaluates to 2, not 1; 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.

Full PCEP-30-02 Practice