Step 1: Global Variable
x = 100Here, a global variable x is created with value 100.
Step 2: Inside test()
-
Python sees the line x = 50 inside the function.
-
Because of this, Python treats x as a local variable within test().
-
Even though the print(x) comes before x = 50, Python already marks x as a local variable during compilation.
Step 3: Execution
-
When print(x) runs, Python tries to print the local x.
-
But local x is not yet assigned a value (since x = 50 comes later).
-
This causes an UnboundLocalError.
Error Message
UnboundLocalError: local variable 'x' referenced before assignment✅ In simple words:
Even though x = 100 exists globally, the function test() creates a local x (because of the assignment x = 50).
When you try to print x before assigning it, Python complains.
๐ If you want to fix it and use the global x, you can do:
This will print 100 and then change global x to 50.


0 Comments:
Post a Comment