Lesson 3 of 5 · Functions · 2 min read · Updated

Scope: where a name lives

Why a variable inside a function is not the one outside, and what global really does.

python
count = 10

def show():
    count = 99
    print("inside:", count)

show()
print("outside:", count)
Output
inside: 99
outside: 10

Assigning to a name inside a function creates a local variable that exists only while the function runs. The count inside is a different variable from the one outside, even with the same name. That is a feature: a function cannot accidentally wreck your other variables.

How Python finds a name

  • Local — inside the current function.
  • Enclosing — inside any function this one is nested in.
  • Global — at the top level of the file.
  • Built-in — names Python provides, such as print and len.

Python searches in that order — LEGB — and uses the first match. Reading a global from inside a function works without any extra keyword.

Changing a global

python
total = 0

def add(n):
    global total
    total += n

add(5)
add(7)
print(total)
Output
12

Warning

Without the global line, total += n raises UnboundLocalError: the assignment makes total local, and a local has no value yet to add to. Globals that functions change are hard to follow, though — passing values in and returning results is almost always better.

python
def add(total, n):
    return total + n

total = 0
total = add(total, 5)
total = add(total, 7)
print(total)
Output
12

x = 1, then a function does x = 2 without global. After calling it, what is x outside?

Try this now

  1. Predict the output of a function that prints a global before and after defining a local with the same name, then run it and read the error.
  2. Rewrite a small program that uses a global counter so the function returns the new count instead.

Create a free account to save your progress, or sign in.