nerdexam
Python_Institute

PCEP-30-02 · Question #213

``python def func(x): global y y = x * x return y func(2) print(y) `` What is the expected output of the following code?

The correct answer is D. 4. Option D (4) is correct because the global y declaration inside func causes the assignment y = x x (i.e., 2 2 = 4) to write into the global scope rather than a local one, so y persists after the function returns and print(y) outputs 4. Option A (2) is wrong because x * x where…

Question

def func(x):
 global y
 y = x * x
 return y

func(2)
print(y)
What is the expected output of the following code?

Options

  • A2
  • BNone
  • CThe code is erroneous.
  • D4

How the community answered

(42 responses)
  • A
    5% (2)
  • B
    5% (2)
  • C
    17% (7)
  • D
    74% (31)

Explanation

Option D (4) is correct because the global y declaration inside func causes the assignment y = x * x (i.e., 2 * 2 = 4) to write into the global scope rather than a local one, so y persists after the function returns and print(y) outputs 4.

Option A (2) is wrong because x * x where x = 2 evaluates to 4, not 2 - squaring, not doubling. Option B (None) is wrong because without global y, the variable would be local and print(y) would raise a NameError; the global keyword is precisely what makes y visible outside the function. Option C is wrong because global y is perfectly valid Python syntax - you don't need to declare y globally before the function runs; the assignment inside the function creates it.

Memory tip: Think of global as "broadcasting" a variable from inside a function to the entire module - once set, anyone outside can read it, just like a global announcement.

Community Discussion

No community discussion yet for this question.

Full PCEP-30-02 Practice