This is a classic Python scope trap. Let’s go step by step.
Code:
Step 1: Look at the function test()
-
Inside test, Python sees an assignment:
y = 20 -
Because of this assignment, Python treats y as a local variable for the entire function (even before it’s assigned).
-
This is due to Python’s scope rules (LEGB):
-
Local (inside function)
-
Enclosed (inside outer function)
-
Global (module-level)
-
Built-in
-
Since y = 20 exists, Python marks y as local inside test.
Step 2: The print(y) line
-
At this point, Python tries to use the local y (because assignment makes it local).
-
But the local y has not been assigned yet when print(y) runs.
Step 3: Result
This leads to:
UnboundLocalError: local variable 'y' referenced before assignment✅ Answer: It raises UnboundLocalError.
๐ If you want it to print the global y = 50, you’d need to explicitly declare it:


0 Comments:
Post a Comment