global — Easy Examples
Declares a variable inside a function as belonging to the global scope
Access and modify global variables
Using global to change module-level variables from inside a function.
python
count = 0 def increment(): global count count += 1 increment() increment() increment() print(f"Count: {count}") # Without global, assignment creates a local variable x = "global" def no_global(): x = "local" # creates a new local x print(f"Inside: {x}") no_global() print(f"Outside: {x}")
Expected Output
Count: 3 Inside: local Outside: global
Without 'global', assigning to a variable inside a function creates a local variable. 'global' tells Python to use the module-level variable instead.
Want to try these examples interactively?
Open Easy Playground