Global Variable in Python

Level 397 keystrokes

This uses the global keyword to modify a variable defined outside the function scope.

Python code

# A module-level (global) variable
1counter = 0
2
# A function that changes the global counter
3def increment():
# Without global, counter += 1 would create a local variable and raise UnboundLocalError
4 global counter
# Adds 1 to the global counter
5 counter += 1
6
# Two calls: counter goes 0 → 1 → 2
7increment()
8increment()
# Prints 2
9print(counter)

Output

2
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • (× 4
  • )× 4
  • =× 2
  • :× 1
  • +× 1

More Python examples at level 3

← Python typing practice