DriversRecommendedOutdated drivers can make a good PC feel brokenScan driver issues before chasing fixes manually.Scan NowOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk7 min

Python NameError: name is not defined (Every Cause and Fix)

Python raises NameError when it cannot resolve a bare name at the point where it is used. Here are the six causes, how to read the traceback, and the fix for each.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

The message NameError: name 'x' is not defined means Python tried to look up the unqualified name x at the point where your code uses it and found no binding for it in any visible scope. The fix is to find where that name should be created or imported, confirm that the binding runs before the use, and confirm the spelling matches exactly. The sections below walk through each cause in the order you are most likely to meet it.

What the error is telling you

Python creates a name through a binding operation: an assignment, a def or class statement, a function parameter, an import, or a similar construct. When Python evaluates a bare name and cannot resolve it, it raises NameError, and the message includes the name it could not find. The Python language reference states the general rule plainly: “When a name is not found at all, a NameError exception is raised.”

Two details matter when you read the message. First, the name in the message is the one Python saw at that point in execution, so a typo appears exactly as typed. Second, the error is about resolution at runtime, which means a name can be perfectly valid in one part of a file and still fail in another.

Read the traceback before changing code

The traceback shows the chain of calls that led to the failure. The last frame that belongs to your own code is the most useful one, because it shows the exact line and the expression that failed.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Scroll to the bottom of the traceback and note the file name and line number of the last frame from your project, not from the standard library or a third-party package.
  2. Open that file at that line and find the bare name quoted in the error message. Compare the spelling character by character.
  3. Decide whether that line is inside a function, at module level, or inside a class body. The scope you are in determines where the name must be bound.
  4. Search the file for the place where the name is assigned, defined, or imported, and confirm that this place runs before the failing line.

In an interactive session, such as a REPL or a notebook, the traceback often points to a cell or input line rather than a file. The same four steps apply; the difference is that the “where it is bound” check usually means checking which cells have actually run.

Causes and fixes

1. Misspelled or inconsistently named identifier

Python identifiers are case-sensitive, so Total, total, and TOTAL are three different names. A single letter off is enough to trigger the error.

total = 10
print(totl)   # NameError: name 'totl' is not defined

Fix: Correct the spelling at the point of use, or rename the binding so both sides match. Some editors and interpreters offer a “Did you mean” suggestion. Treat that as a lead to check against your code, not as a guaranteed correction, because the suggested name may be a different variable entirely.

2. The name is never assigned or defined

Sometimes the code simply never creates the name. A variable may have been removed during refactoring, or a branch that sets it may never execute.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
if user_is_admin:
    level = "full"
print(level)   # NameError if user_is_admin is False

Fix: Give the name a value on every path that can reach the use. A default assignment before the if block is the simplest guarantee:

level = "limited"
if user_is_admin:
    level = "full"
print(level)

3. Missing import or wrong imported name

A name that belongs to a module does not appear in your namespace until you import it. Importing the module is not the same as importing one of its members.

import math
print(sqrt(16))        # NameError: name 'sqrt' is not defined
print(math.sqrt(16))   # 4.0

Fix: Either use the qualified name (math.sqrt) or import the object directly (from math import sqrt). Check the spelling of the module and any alias, because import numpy as np binds np, not numpy. The language reference lists import statements among the operations that bind names, so the import has to execute before the use.

4. Scope mismatch between functions and modules

A name bound inside one function is local to that function. Another function cannot see it, even if both live in the same file.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
def load():
    config = {"debug": True}

def run():
    print(config)   # NameError: name 'config' is not defined

Fix: The usual correction is to pass the value as an argument, or return it from the function that creates it:

def load():
    return {"debug": True}

def run(config):
    print(config)

run(load())

Use global only when a function is intended to read or rebind a name in the module namespace, and use nonlocal only for a name bound in an enclosing function. Declaring these keywords by habit tends to hide the real design problem.

5. Local variable read before it is assigned

This case looks like a missing name but raises a more specific error. If a function contains any binding operation for a name, Python treats every reference to that name inside the function as local, unless the function declares it global or nonlocal. Reading the name before the local receives a value raises UnboundLocalError, which the language reference defines as a subclass of NameError: “UnboundLocalError is a subclass of NameError.”

counter = 0

def bump():
    counter += 1    # UnboundLocalError: the augmented assignment makes 'counter' local

bump()

Fix: Choose one of two approaches. Pass the value in and return the updated result, which is usually clearer:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
counter = 0

def bump(count):
    return count + 1

counter = bump(counter)

Or, if the function really must rebind the module-level name, declare it explicitly with global counter at the top of the function. Because the error is a NameError subclass, an except NameError clause also catches it, which can hide the distinction. Catch UnboundLocalError first when you need to handle it separately.

6. Notebook or interactive execution order

In a notebook, a name may be defined in a cell that has not run in the current session, or a kernel restart may have cleared it. Cells can be run out of order, so the cell that defines a name may appear above the failing cell on screen but may never have executed.

Fix: Restart the kernel and run all cells from the top, or re-run the defining cell and then the failing one. If the error appears only after a restart, the definition lives in a cell that depends on execution order rather than on the file contents. This is practical troubleshooting guidance: the language rule is that a name must be bound before it is used, and the notebook makes it easy to violate that rule without noticing.

Quick reference: symptom to cause

What you see Likely cause Where to fix it
name 'x' is not defined, and x is visibly spelled differently in the definition Misspelling or case mismatch The failing line, or the definition
name 'x' is not defined, and no assignment for x exists anywhere Name never bound Before the first use
name 'f' is not defined for a function from a module Missing import or unqualified member Top of the file, or qualify the call
name 'x' is not defined, and x is bound in a different function Scope mismatch Pass as argument or return from the creating function
UnboundLocalError on a name that is also bound later in the same function Local read before assignment Inside the function, or declare global/nonlocal
Error appears only after a restart or in an out-of-order notebook Execution order Re-run definitions in order
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Scope rules worth knowing precisely

A common shortcut is to describe every Python name lookup with a single universal order of scopes. That is useful as a memory aid but not accurate in every case. Class bodies, comprehensions, annotation scopes, and the global and nonlocal declarations each have behavior that the language reference specifies in detail. When a lookup surprises you, read the scope section of the reference for the construct involved rather than assuming a general rule applies.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For global references, the reference describes lookup in the module’s global namespace and then in the built-in names. A built-in such as len never raises this error unless it has been shadowed by your own binding, so a stray len = 5 at module level can cause confusing failures elsewhere in the file.

Inspecting the missing name in code

Python 3.10 added a name attribute to NameError exceptions. If your program catches the error, you can read the unresolved name directly rather than parsing the message:

try:
    print(totl)
except NameError as err:
    print(err.name)   # 'totl'

This is useful for logging and tests. On Python versions earlier than 3.10, the attribute is not available, so code that relies on it should check the interpreter version or fall back to reading the message text. Exact wording of messages can also differ between versions, so avoid matching on full message strings in production code.

Reference material for these rules is the Python language reference, particularly the Execution model section that covers naming and binding, and the Python tutorial’s explanation of tracebacks.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use the traceback to locate the failing line, check where the name is bound, and match the scenario above. In most cases one of the six causes will account for the error, and the fix is a single line.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
PC Slower Than It Used to Be?Free scan - under a minute
Crashes, No Sound, or Screen Glitches?Free driver scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.