What's going on?
You're defining a variable x = 0 outside the function (global scope), and then trying to increment x inside the function.
What happens when you run this?
You'll get an error:
❓ Why?
Python thinks x inside the function is a local variable, because you're assigning to it with x += 1. However, you're also trying to read its value before the assignment — and since there's no local x defined yet, Python throws an error.
✅ How to fix it?
You can fix it by telling Python that x inside func() refers to the global x, using the global keyword:
๐ข Output:
Now x += 1 modifies the global variable x.
Key Concept:
When you assign to a variable inside a function, Python assumes it's local, unless you declare it as global or nonlocal.


0 Comments:
Post a Comment