Tutorials Logic, IN info@tutorialslogic.com

NameError in Python name is not defined Fix: Causes and Fixes

Python NameError

NameError happens when Python reaches a name that it cannot find in the current scope, imported modules, or built-in names.

The usual causes are using a variable before assignment, misspelling a name, changing letter case, forgetting an import, or reading a local variable from the wrong scope.

To debug it, read the final traceback line, copy the missing name exactly, then search where that name should have been defined.

What NameError Means

The NameError occurs when you try to use a variable, function, or module name that Python doesn't recognize. This means the name hasn't been defined yet, is misspelled, or is out of scope.

Missing Names

  • Using a variable before defining it
  • Typo in variable or function name
  • Variable is out of scope (defined in different function/block)
  • Forgetting to import a module
  • Case sensitivity issues (Python is case-sensitive)

Define Names First

Create the Variable First

Create the Variable First
# Bad lookup: message is used before it exists
print(message)  # NameError: name 'message' is not defined

# Fixed lookup: define message before using it
message = "Hello, World!"
print(message)

# Check for typos
username = "John"
print(username)  # Not 'userName' or 'user_name'

NameError Cases

  • The most common cause - trying to use a variable before it has been assigned a value.
  • Misspelling a variable name or using incorrect case (Python is case-sensitive).
  • Trying to access a variable defined inside a function from outside, or vice versa.
  • Using a module or function without importing it first.
  • Forgetting quotes around strings makes Python think it's a variable name.

Variable Used Before Assignment

Variable Used Before Assignment
print(total)  # NameError!
total = 100

Assign the Variable First

Assign the Variable First
total = 100  # Define first
print(total)  # Then use

Misspelled Variable Name

Misspelled Variable Name
user_name = "Alice"
print(username)  # NameError: 'username' vs 'user_name'

firstName = "Bob"
print(firstname)  # NameError: case mismatch!

Use the Same Spelling Everywhere

Use the Same Spelling Everywhere
user_name = "Alice"
print(user_name)  # Exact match

firstName = "Bob"
print(firstName)  # Exact case match

# Use consistent naming convention (snake_case recommended)
user_name = "Alice"
first_name = "Bob"

Local Variable Read Outside Function

Local Variable Read Outside Function
def calculate():
    result = 100

print(result)  # NameError: result is local to calculate()

Return the Local Value

Return the Local Value
# Return the value from the function
def calculate():
    result = 100
    return result

result = calculate()
print(result)

# Alternative: use global only when shared state is intentional
result = 0

def calculate():
    global result
    result = 100

calculate()
print(result)

# Simple case: define the value outside the function
result = 100

def calculate():
    print(result)  # Can read global variable

calculate()

Module Used Before Import

Module Used Before Import
result = math.sqrt(16)  # NameError: name 'math' is not defined

data = json.loads('{"key": "value"}')  # NameError!

Import the Module First

Import the Module First
import math
result = math.sqrt(16)

import json
data = json.loads('{"key": "value"}')

# Or import specific functions
from math import sqrt
result = sqrt(16)

from json import loads
data = loads('{"key": "value"}')

String Missing Quotes

String Missing Quotes
name = Alice  # NameError: name 'Alice' is not defined
print(Hello)  # NameError!

Wrap Text in Quotes

Wrap Text in Quotes
name = "Alice"  # Add quotes for strings
print("Hello")  # Strings need quotes

Prevent NameError

  • Define before use - Always define variables before using them
  • Check spelling - Use autocomplete in your IDE to avoid typos
  • Be consistent with naming - Use snake_case for variables (PEP 8)
  • Import at the top - Put all imports at the beginning of your file
  • Use meaningful names - Avoid single letters except for loops
  • Use linters - Tools like pylint catch undefined names before runtime
  • Understand scope - Learn about local, global, and nonlocal variables

Trace the Missing Name

When NameError appears, do not guess. Read the missing name in the final traceback line, then search for that exact spelling in the file.

If the spelling is correct, check order next. Python must execute the assignment, function definition, class definition, or import before the name is used.

If the name exists inside a function, remember that local variables stay inside that function unless you return them or pass them to another function.

  • Copy the missing name exactly from the traceback.
  • Check spelling and letter case.
  • Confirm the name is defined before it is used.
  • Check imports and function scope before changing unrelated code.
NameError debugging check

Can You Find the Missing Name?

5 checks
  • The NameError occurs when you try to use a variable, function, or module name that Python doesn't recognize.
  • This means the name hasn't been defined yet, is misspelled, or is out of scope.
  • Read the failing line for a name that is reached before assignment.
  • Compare spelling and capitalization at the definition and use sites.
  • Check whether the name belongs to a local, enclosing, module, or built-in scope.

Questions About NameError

NameError occurs when you try to use a variable, function, or module name that hasn't been defined, is misspelled, or is out of scope.

Define the variable before using it, check for typos, ensure correct case, import required modules, or check if the variable is in the correct scope.

Check for typos, case sensitivity (Python is case-sensitive), or scope issues. The variable might be defined in a different function or block.

Browse Free Tutorials

Explore 500+ free tutorials across 20+ languages and frameworks.