Code Explanation:
1. Global Variable Declaration
x = 14
A variable x is created in the global scope.
Its value is 14.
This means x can be accessed anywhere in the program unless shadowed locally.
⚙️ 2. Function Definition
def func():
A function named func is defined.
No parameters are passed to this function.
๐จ️ 3. First Statement Inside Function
print(x)
Python looks for x inside the function first (local scope).
But notice: later in the function, x = 5 exists.
Because of that assignment, Python treats x as a local variable throughout the function.
๐ Important rule:
If a variable is assigned anywhere inside a function, Python considers it local to that function (unless declared global).
❗ 4. Local Assignment
x = 5
This creates a local variable x inside func.
It does NOT affect the global x.
๐จ 5. Function Call
func()
When the function runs:
Python sees x = 5 → decides x is local
Then tries print(x) BEFORE assigning it
๐ฅ 6. Error Occurs
You will get:
UnboundLocalError: local variable 'x' referenced before assignment
Why?
Python thinks x is local
But print(x) tries to use it before it's assigned
Final Output:
Error

0 Comments:
Post a Comment