nerdexam
Python_Institute

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

What is the expected output of the following code?
def func():
 print(x + 1, end=' ')

x = 1
func()
print(x)

Options

  • A21
  • B22
  • C11
  • D12

How the community answered

(27 responses)
  • A
    81% (22)
  • B
    4% (1)
  • C
    4% (1)
  • D
    11% (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 x to equal 2 when the second print runs, but func() never modifies x - it only reads it.
  • C (1 1): Would require x + 1 to equal 1, implying x=0, which contradicts the assignment x = 1.
  • D (1 2): Would require the outputs to be swapped or x+1 to 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.

Full PCEP-30-02 Practice