Skip to content

Module 9 · Functions — topic 13 of 19

Local variables

Variables created inside a function exist only during that call; why that isolation is valuable, and the UnboundLocalError caused by assigning to a name used before assignment.

Beginner 8 min read·Lesson 138 of 306 in Python Programming

Learning objectives

  • Identify which names are local to a function
  • Explain why locals don't clash between functions
  • Diagnose UnboundLocalError

Definition

A local variable is a name assigned inside a function body (including its parameters). It belongs to the function's local scope, is created fresh for each call and disappears when the call returns.

Introduction

If two functions both use a variable called total, they don't interfere: each has its own local total. This isolation is what makes functions safe to combine.

Why it matters

Local variables let you reason about a function on its own. Understanding the 'assignment makes a name local' rule explains the confusing UnboundLocalError.

Detailed explanation

Any name that is assigned anywhere in a function body — with =, +=, a for loop target, import or def — is local to that function for the whole body.

Parameters are locals too.

Locals are created each time the function is called and destroyed when it returns; values aren't remembered between calls (use a return value, an attribute or a closure for that).

A local with the same name as a global shadows it inside the function; the global is unaffected.

If a name is local (because it's assigned somewhere in the function) but you read it before the assignment runs, Python raises UnboundLocalError — even if a global with that name exists.

Syntax

Python
def add_tax(price):
rate = 0.18 # local
total = price * (1 + rate) # local
return total
# rate and total don't exist out here
  • Assignment inside a function creates a local.
  • Locals vanish when the call ends.

Code examples

Locals are private

Python
def add_tax(price):
rate = 0.18
return round(price * (1 + rate), 2)
print(add_tax(100))
try:
print(rate)
except NameError as e:
print("NameError:", e)
Output
118.0
NameError: name 'rate' is not defined

Shadowing a global

Python
total = 1000
def order_total(prices):
total = sum(prices) # a new local, not the global
return total
print(order_total([120, 80]), total)
Output
200 1000

More examples

UnboundLocalError explained

Python
counter = 0
def broken():
counter += 1 # assignment makes counter local, but it has no value yet
return counter
def fixed(current):
return current + 1
try:
broken()
except UnboundLocalError as e:
print(type(e).__name__ + ":", e)
counter = fixed(counter)
counter = fixed(counter)
print(counter)
Output
UnboundLocalError: cannot access local variable 'counter' where it is not associated with a value
2

Step-by-step explanation

  • Because broken assigns to counter, the compiler treats counter as local throughout the function.
  • counter += 1 needs to read the local first, but it hasn't been assigned: UnboundLocalError.
  • fixed takes the value as a parameter and returns the new value, so no shared state is needed.

Expected output

Running “UnboundLocalError explained” prints exactly:

TextOutput
UnboundLocalError: cannot access local variable 'counter' where it is not associated with a value
2

Practical applications

  • Temporary results, loop counters and helpers inside functions are locals.
  • Isolation means library functions can't accidentally change your variables.

Best practices

  • Keep variables as local as possible.
  • Pass data in as parameters and return results.
  • Avoid reusing global names for locals; it confuses readers.

Common mistakes

Expecting locals to persist

Avoid

def count_calls():
calls = 0
calls += 1
return calls # always 1

Prefer

Pass state in and return it, or use a class attribute.

Locals are recreated on each call.

Important notes

  • The exact UnboundLocalError message shown is from Python 3.11+; older versions say "local variable 'counter' referenced before assignment".

Key takeaways

  • Names assigned in a function are local to it.
  • Locals exist only during one call.
  • Reading a local before assigning it raises UnboundLocalError.

Try it yourself

  1. 1
    Write two functions that each use a variable named result and show they don't interfere.
  2. 2
    Fix a function that raises UnboundLocalError by passing the value in and returning the new one.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

1 question test this exact topic. Answers and explanations are revealed after you submit.

  • ModerateWhat happens when f() is called?
Practise this topic