nerdexam
Python_Institute

PCEP-30-02 · Question #227

A variable defined outside a function:

The correct answer is A. may be read, but not written (something more is needed to do so). In Python, a variable defined in the outer (global) scope can be read inside a function without any special declaration, but writing to it requires the global keyword - making A correct. Without global, assigning to the variable inside the function simply creates a new local…

Question

A variable defined outside a function:

Options

  • Amay be read, but not written (something more is needed to do so)
  • Bmay not be accessed in any way inside the function
  • Cmay be freely accessed inside the function

How the community answered

(24 responses)
  • A
    83% (20)
  • B
    13% (3)
  • C
    4% (1)

Explanation

In Python, a variable defined in the outer (global) scope can be read inside a function without any special declaration, but writing to it requires the global keyword - making A correct. Without global, assigning to the variable inside the function simply creates a new local variable that shadows the outer one, leaving the original unchanged.

Option B is wrong because Python's scoping rules (LEGB: Local → Enclosing → Global → Built-in) allow functions to look up and read outer-scope names freely. Option C overstates the access - "freely" implies you can also write to it, which you cannot without global (or nonlocal for enclosing scopes).

Memory tip: Think of the outer variable as a read-only library book - anyone can read it, but to check it out and modify it, you need to sign the global declaration first.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice