Step-by-Step Explanation
-
Define a global variable:
-
A variable count is initialized in the global scope with value 0.
-
-
Define a function counter:
-
The global keyword tells Python:
"Use the count variable from the global scope, not a new local one."
-
-
First function call:
count += 1 → count = 0 + 1 → count = 1
-
Second function call:
count += 1 → count = 1 + 1 → count = 2
-
Print the result:
-
This prints:
-
✅ Output:
Key Concept:
global allows a function to modify a variable defined outside the function.
-
Without global, Python would assume count is local, and you'd get an UnboundLocalError.


0 Comments:
Post a Comment