CodeMIRAI
0 XP

Variable scope

2 min read 6 runnable examples Quiz included

Scope is where in your program a name can be seen. Variables created inside a function are different from those created outside it.

Local variables

A variable created inside a function is local: it exists only while the function runs, and only inside it.

Python
def make_greeting():
    message = "Hello from inside"   # local
    print(message)

make_greeting()
print(message)

Each call gets fresh local variables, so functions don't trip over each other's names.

Global variables

A variable created at the top level of a file is global. Functions can read it:

Python
tax_rate = 0.18      # global

def price_with_tax(price):
    return price * (1 + tax_rate)

print(price_with_tax(100))

Same name, different variables

Assigning to a name inside a function creates a new local variable, even if a global with the same name exists:

Python
count = 10

def reset():
    count = 0           # a new local variable; the global is untouched
    print("inside:", count)

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

Changing a global: the global keyword

To assign to a global from inside a function, declare it with global:

Python
visits = 0

def record_visit():
    global visits
    visits += 1

record_visit()
record_visit()
print(visits)

It works, but it makes code harder to follow, because any function might change the value. The cleaner pattern is to pass values in and return results:

Python
def record_visit(visits):
    return visits + 1

visits = 0
visits = record_visit(visits)
visits = record_visit(visits)
print(visits)

How Python finds a name: LEGB

When you use a name, Python searches four scopes in order:

Built-in: print, len, rangeGlobal: names at the top of the fileEnclosing: the outer functionLocal: inside this functionPython looks for a name Local → Enclosing → Global → Built-in, and stops at the first match
A name assigned inside a function is local to it unless you declare it global or nonlocal.
  1. Local: inside the current function
  2. Enclosing: inside any function that contains this one
  3. Global: the top level of the file
  4. Built-in: Python's own names, like len and print

The first match wins. That's why naming your own variable list or print is a bad idea: it hides the built-in.

Python
def outer():
    label = "enclosing"
    def inner():
        print(label)        # found in the enclosing scope
    inner()

outer()
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.