Module 4 · Scopes in Python · Lesson 1 of 3
Functions and scopes
Every variable has a scope: the part of your program where that name actually exists. The big rule for functions is simple — a variable you create inside a function is local. It's born when the function runs and vanishes the instant it returns, and the outside world can never see it.
That's why reaching for a function's local variable from outside is a NameError — by then it no longer exists. Locals keep functions self-contained: two functions can each have a variable called i without ever colliding.
Variables defined at the top level of your file are global, and a function can read them freely. But watch the catch: if a function assigns to a name, Python treats that name as a brand-new local for the whole function — a local that shadows the global and leaves the global untouched.
So reading a global is easy; changing one from inside a function takes a deliberate extra step. That step is the global keyword — next.