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.”
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.
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.
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.