← Python lessons

Python Variable Scope: Local and Global Variables

Part of a free Python course — sign up to save your progress and get AI hints.Sign up free

Scope is where a name can be used. A local variable exists only inside one function call. A global variable is made at the top level.

Read Parameters & Return first.

This lesson explains one thing: why names made inside a function stay inside it, and how to get values in and out. Every block below runs on its own and prints the result shown under it.

Local variables stay inside the function

A name assigned inside a function is local. It is gone once the call ends.

def make_total():
    total = 5
    print("inside:", total)

make_total()
print(total)  # this line raises NameError: name 'total' is not defined

This prints inside: 5, then fails. Return the value if the caller needs it.

A function can read a global variable

If a function only reads a name it never assigns, Python looks it up at the top level.

tax = 10

def with_tax(price):
    return price + tax

print(with_tax(50))

This prints 60. It works, but with_tax now depends on a name outside it. Passing tax as a parameter makes that clear.

Assigning inside makes a new local name

Assigning a name inside a function makes a local one, even if a global has the same name. The global does not change.

count = 0

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

reset()
print("outside:", count)

This prints inside: 99 then outside: 0. The two count names are different variables.

Changing a global gives UnboundLocalError

Because of that rule, count += 1 inside a function treats count as local. It has no value yet, so the line fails.

count = 0

def add_one():
    count += 1  # this line raises UnboundLocalError

add_one()

The keyword global count at the top of the function would let it change the global. Prefer a parameter and a return instead: the function then works on any value and is easy to test.

def add_one(count):
    return count + 1

count = 0
count = add_one(count)
count = add_one(count)
print(count)

This prints 2. The caller decides where the result is stored.

Note: This lesson leaves out nonlocal, which changes a name in an outer function. See Functions as values for nested functions.

See also: Defining Functions.

Your turn

This add_points changes a global with global score. Rewrite it to take score and points as parameters and return the new score, with no global. Then add 5 and 3 to score and print it.

score = 0

def add_points(points):
    global score
    score += points

# rewrite add_points(score, points) to return the new score,
# then store add_points(score, 5) and add_points(score, 3) in score
print(score)

Expected output

8