nerdexam
Python_Institute

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

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)

Options

  • A
    1. x: 42
    2. x: 42
    3. x: 42
  • BNone of the above.
  • C
    1. x: 42
    2. x: 23
    3. x: 23
  • D
    1. x: 42
    2. x: 23
    3. x: 42

How the community answered

(41 responses)
  • A
    5% (2)
  • B
    2% (1)
  • C
    80% (33)
  • D
    12% (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 = 23 inside the function has no effect, which would only be true if global x were absent (in which case Python would raise an UnboundLocalError before 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 x means 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.

Full PCEP-30-02 Practice