Real‑world examples of undeclared variable errors in Python

If you write Python long enough, you will absolutely trip over undeclared variables. It happens to beginners and senior engineers alike. In this guide, we’ll walk through real, practical examples of undeclared variable errors in Python, show why they happen, and how to fix them without tearing your hair out. These are not toy snippets; they’re examples pulled from the kinds of bugs you actually see in scripts, data pipelines, and web backends. By the end, you’ll recognize patterns and know exactly where to look when that dreaded `NameError` shows up. We’ll start with concrete examples of undeclared variable errors in Python, then move into patterns involving scopes, typos, refactors, and async code. Along the way, we’ll contrast behavior between Python versions, point to good practices from the wider software engineering world, and highlight how modern tools (linters, type checkers, IDEs) in 2024–2025 catch these bugs earlier. If you’ve ever stared at `NameError: name 'x' is not defined` wondering what you missed, this article is for you.
Written by
Jamie
Published

Straightforward examples of undeclared variable errors in Python

Let’s start with the most obvious pattern: you try to use a name that Python has never seen. This produces a NameError, the classic signal of an undeclared variable.

## Example 1: Simple typo
user_count = 10
print(user_cout)

Running this gives:

NameError: name 'user_cout' is not defined

This is the textbook example of an undeclared variable error in Python: you declared user_count, but you used user_cout. Python doesn’t silently guess; it just complains.

Here’s another minimal example of an undeclared variable error that shows up in quick scripts:

## Example 2: Variable used before assignment in the file
print(total)

total = 42

Even though total is defined later, Python executes top to bottom. When it hits print(total), there is no total in the current scope yet, so again you get NameError: name 'total' is not defined.

These basic cases may look trivial, but real examples in production code are often just slightly more complex versions of these same mistakes.


Real examples of undeclared variable errors in Python functions and scopes

Scopes are where undeclared variable errors get interesting. A very common example of this bug appears in functions when you accidentally shadow a variable or forget to pass it in.

## Example 3: Using a global without declaring it global
count = 0

def increment():
    count = count + 1  # Trying to modify the outer `count`

increment()

This doesn’t behave the way many people expect. Python sees count assigned inside the function, so it treats count as a local variable. When it tries to evaluate count = count + 1, it needs the right‑hand count first, but that local count isn’t defined yet. The result:

UnboundLocalError: local variable 'count' referenced before assignment

UnboundLocalError is a subclass of NameError. Conceptually, it’s still an undeclared variable problem: you’re using a name that doesn’t exist in the local scope at the time of access.

The correct fix is either to pass count as a parameter or explicitly mark it as global:

count = 0

def increment():
    global count
    count = count + 1

Or better:

def increment(count):
    return count + 1

count = increment(count)

Another example of undeclared variable errors in Python functions shows up when refactoring:

## Example 4: Forgot to pass an argument after refactor

def send_email(message, recipient):
    print(f"Sending to {recipient}: {message}")

## Later you refactor and add `subject`, but forget to update all call sites

def notify_user(user):
    subject = "Welcome!"
    message = "Thanks for signing up"
    send_email(message, user.email)  # subject not passed

## Then inside send_email you try to use subject

def send_email(message, recipient):
    print(f"Subject: {subject}")  # NameError here
    print(f"Sending to {recipient}: {message}")

Here, subject is only defined in notify_user, not in send_email. This is another example of an undeclared variable error in Python caused by scope: the variable lives in a different function.


Best examples of undeclared variable errors in Python from loops and conditionals

Loops and conditionals tend to hide undeclared variables because not all branches execute in every run. Some of the best examples of sneaky undeclared variable errors in Python come from if blocks that don’t always run.

## Example 5: Variable defined only in one branch

def get_discounted_price(price, is_vip):
    if is_vip:
        discount = 0.2
    return price * (1 - discount)

get_discounted_price(100, False)

If is_vip is False, the if block never runs, so discount is never created. When Python reaches price * (1 - discount), there is no discount in the current scope, and you get NameError: name 'discount' is not defined.

A safer pattern is to initialize the variable before the conditional:

def get_discounted_price(price, is_vip):
    discount = 0.0
    if is_vip:
        discount = 0.2
    return price * (1 - discount)

Another real example of an undeclared variable error in Python loops appears when you assume a variable will be set inside the loop, but the loop never runs:

## Example 6: Loop body never executes

def last_positive(numbers):
    for n in numbers:
        if n > 0:
            last = n
    return last

last_positive([])

With an empty list, the for loop body never executes, so last is never created. The return last line then fails with a NameError. This is a classic example of why you should initialize variables to a default value before loops:

def last_positive(numbers):
    last = None
    for n in numbers:
        if n > 0:
            last = n
    return last

Examples include async code, threads, and modern Python patterns

Python in 2024–2025 is full of async code, background tasks, and dynamic imports. These newer patterns create fresh examples of undeclared variable errors in Python that you might not see in older tutorials.

Here’s an async example of an undeclared variable error in Python where a typo appears inside an async function:

import asyncio

async def fetch_data():
    response = {"status": 200}
    return reponse  # Typo here

async def main():
    data = await fetch_data()
    print(data)

asyncio.run(main())

When fetch_data runs, Python hits return reponse, which is never declared. That triggers NameError: name 'reponse' is not defined. This is structurally the same as earlier examples, but now it’s buried inside async code that only runs under certain conditions.

Threads can surface similar bugs. Imagine a worker thread referencing a variable that was only defined in the main thread:

## Example 7: Thread function using a missing global

import threading

config = {"retries": 3}

def worker():
    print(settings["retries"])  # `settings` is not defined

thread = threading.Thread(target=worker)
thread.start()
thread.join()

Here, you meant to use config but wrote settings. Because settings is never declared anywhere, the worker thread hits a NameError when it runs. In real systems, this might only show up under production load when certain code paths finally execute.

Dynamic imports and plug‑in patterns can also produce interesting examples of undeclared variable errors in Python. Imagine a plugin that expects a symbol to exist in the global namespace:

## plugin.py

def run():
    print(API_KEY)  # Assumes API_KEY is defined where this is imported

If the main application forgets to define API_KEY before importing and running the plugin, calling plugin.run() will fail with a NameError. This is another example of an undeclared variable error in Python caused by loose contracts between modules.


Real examples of undeclared variable errors during refactors and migrations

Refactors are where undeclared variable bugs love to hide. You rename a variable in one place but miss another, or you move code between modules and forget imports.

Here’s a very common example of an undeclared variable error in Python during a rename:

## Before refactor
max_retries = 5
print(max_retries)

## After partial refactor
max_attempts = 5
print(max_retries)  # still using old name

You intended to rename max_retries to max_attempts, but you only changed the definition. The print statement still uses the old name, which now no longer exists. That triggers NameError: name 'max_retries' is not defined.

Another real‑world example includes configuration variables when migrating from environment variables to a config object:

## Old style
API_URL = os.environ["API_URL"]

## New style
config = {"api_url": os.environ["API_URL"]}

## Somewhere later in the code
print(API_URL)

You removed the old API_URL assignment but left the usage. The name is now undeclared. This is where static analysis tools really help.

Tools like pylint, flake8, and mypy are widely used in 2024–2025 to catch undeclared variable errors before runtime. For example, pylint has a used-before-assignment and undefined-variable check that flags many of the examples of undeclared variable errors in Python we’ve walked through here.

For a broader view on how static analysis improves software reliability, you can look at discussions from academic and industry sources, such as research available through MIT OpenCourseWare or software engineering courses at Carnegie Mellon University. While these aren’t Python‑only resources, they reinforce why catching undeclared names early is worth the effort.


How to systematically avoid undeclared variable errors in Python

Now that we’ve seen multiple examples of undeclared variable errors in Python, let’s talk about patterns that prevent them.

Initialize before use. Many of the best examples of these bugs come from variables that are only conditionally assigned. Initialize them with a safe default at the top of the function. For instance, set discount = 0.0 before the if block, or last = None before the loop.

Pass data explicitly. Instead of reaching into globals, pass arguments into functions. This avoids the “I thought that variable was visible here” problem that created the count and subject examples earlier.

Use consistent naming. Typos (user_cout, reponse, settings) are responsible for a lot of real examples of undeclared variable errors in Python. Short, consistent names, plus good IDE support, cut these way down.

Adopt linters and type checkers. Modern Python projects (especially in 2024–2025) almost always include a linter in their CI pipeline. Tools like pylint and flake8 will highlight undefined names. mypy adds type checking on top, which often reveals undeclared variables when a name suddenly changes type or disappears. You can see similar recommendations in general software engineering best practices taught in university CS programs, such as those at Harvard University.

Write tests that hit all branches. Many examples of undeclared variable errors only appear when a rarely used branch runs: a False flag, an empty list, an unusual error path. Unit tests that cover these branches will trigger the NameError in a safe environment instead of in production.

While health‑focused organizations like NIH or Mayo Clinic aren’t about Python specifically, they’re good reminders that rigorous testing and validation are standard in any serious field. Software should be no different.


FAQ: short answers and extra examples

Q: Can you show another quick example of an undeclared variable error in Python?
Yes. Here’s a tiny one from a logging scenario:

def log_login(user):
    message = f"User {user} logged in"
    logger.info(msg)  # `msg` was never defined

You meant to log message, but you wrote msg. That’s another everyday example of an undeclared variable error in Python.

Q: Is UnboundLocalError different from NameError?
UnboundLocalError is a subclass of NameError. It happens when Python decides a name is local to a function (because you assign to it) but you try to read it before assigning. Conceptually, it’s still an undeclared variable in that local scope.

Q: Do undeclared variable errors only happen with variables?
No. The same pattern appears with functions and classes. If you call process_data() before defining it in the file, or you delete a function and forget to remove all calls, you’ll get a NameError for that function name.

Q: How can I automatically find examples of undefined names in my project?
Run a linter like pylint or flake8 over your codebase. They scan the abstract syntax tree and report undefined names, missing imports, and variables used before assignment. Many editors and IDEs (VS Code, PyCharm) surface these warnings inline while you type.

Q: Are there performance costs to avoiding undeclared variable errors?
Not in any meaningful way. Initializing variables, passing arguments explicitly, and using clear naming have negligible runtime cost in Python compared with the cost of production outages or data corruption from buggy code.


The bottom line: all of the examples of undeclared variable errors in Python we walked through share the same root cause—a name is used in a scope where it doesn’t exist. Once you train your eye to look for missing initializations, typos, and scope boundaries, these bugs go from mysterious to mildly annoying and easily fixed.

Explore More Compilation Errors

Discover more examples and insights in this category.

View All Compilation Errors