How can I use a global variable in a function?

In Python, if you want to modify a global variable from inside a function, you must explicitly declare it as global inside that function.
If you only read a global variable, you don’t need global—but the moment you assign to it, Python assumes it’s a new local variable unless told otherwise.

Here’s an example:

# Global variable
counter = 0

def increment():
global counter # Tell Python: "Use the global variable, not a new local one"
counter += 1

def show_counter():
print(counter) # Just reading, so no `global` needed

increment()
increment()
show_counter() # Output: 2

Key points:

  • Use global var_name inside the function to write to a global variable.

  • Reading doesn’t require global, but if you both read and write in the same function, you must declare it.

  • Overusing globals can make code harder to debug—often passing values as function parameters is better.