loop
Scopes in Python

Module 4 · Scopes in Python · Lesson 2 of 3

The global keyword

We just saw that assigning to a name inside a function makes a local, leaving any global of the same name alone. Sometimes, though, you really do want a function to change a global. The global keyword tells Python exactly that: global x means “when I write x, I mean the global one.”

global: reach the real one
without global
x = 1
def f():
x = 5
local x = 5
with global
x = 1
def g():
global x
x = 5
↑ changes the global

The difference is one line. Without global, the assignment stays trapped inside the function as a local. With it, the assignment reaches out and changes the variable everyone shares.

Run it yourselfruns in your browser · Python
main.py

A word of caution, though: global is best used sparingly. When a function quietly reaches out and rewrites shared state, your code becomes harder to follow and to debug — the value of x can change for reasons you can't see at the call site.

Run it yourselfruns in your browser · Python
main.py

The cleaner habit, almost always, is the pattern from the last section: pass values in as arguments and hand results back out with return. Reach for global only when you have a genuine reason to.