What's happening here?
-
Global Scope:
Variable x = 10 is defined outside the function, so it's in the global scope. -
Inside func():
Here, you're trying to print x before assigning x = 5.
In Python, any assignment to a variable inside a function makes it a local variable, unless it's explicitly declared global or nonlocal.
So Python treats x as a local variable in func() throughout the function body, even before the line x = 5 is executed.
-
Error:
When print(x) runs, Python is trying to access the local variable x before it has been assigned. This leads to:❌ UnboundLocalError: cannot access local variable 'x' where it is not associated with a value
✅ Fix it
If you want to access the global x, you can do:
Or simply remove the assignment if not needed.
Key Concept
If a variable is assigned anywhere in the function, Python treats it as local throughout that function—unless declared with global or nonlocal.
0 Comments:
Post a Comment