loop
Scopes in Python

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.

Local lives inside; global lives outside
global scope
score = 100
def play():
bonus = 10
↑ can read score (100)
print(bonus)  # NameError: name 'bonus' is not defined

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.

Run it yourselfruns in your browser · Python
main.py

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.

Run it yourselfruns in your browser · Python
main.py

So reading a global is easy; changing one from inside a function takes a deliberate extra step. That step is the global keyword — next.