NameError in Python: Python Errors & Solutions Master Series

NameError in Python Thumbnail

NameError in Python

Python Errors & Solutions Master Series

Introduction

If you're just starting your Python journey, one of the first errors you'll encounter is NameError. Almost every Python programmer—from beginners to experienced developers—has seen this error at some point.

A NameError occurs when Python encounters a variable, function, class, or module name that it doesn't recognize. In simple terms, Python is telling you:

"I don't know what this name refers to."

Although this error may seem confusing initially, it's one of the easiest Python errors to understand and fix once you know how Python looks up names.

In this lesson, you'll learn what a NameError is, why it happens, how Python searches for names, and how to prevent this error in your own programs.

Learning Objectives

By the end of this lesson, you will be able to:
  • Understand what a NameError is.
  • Recognize common situations that trigger it.
  • Learn how Python searches for variables and functions.
  • Understand the concept of variable scope.
  • Read and interpret NameError messages.
  • Write code that avoids this common mistake.

What Is NameError in Python?

A NameError is a built-in Python exception that occurs when you try to use a name that hasn't been defined.

The name can refer to:

A variable
A function
A class
A module
An object

If Python cannot find the requested name anywhere it is allowed to search, it raises a NameError.

Simple Example:

print(age)

Output:

NameError: name 'age' is not defined
In this example, the variable age was never created before it was used. Since Python has no idea what age represents, it raises a NameError.

Why Does Python Raise a NameError?

Python executes your code one line at a time.

Whenever it encounters a variable or function name, it attempts to locate that name in memory.

If it successfully finds the name, execution continues normally.

If it cannot find the name, execution stops and Python raises a NameError.

For example:

name = "SkillDedication"
print(name)

Output:

Coding Bihar
Python already knows what name refers to because it was defined before it was used.

Now consider this example:
print(age)

Output:

NameError: age 'age' is not defined

Since the variable doesn't exist, Python reports an error.


How Python Searches for Names

Understanding how Python searches for names is one of the most important concepts in programming. Whenever Python encounters a name, it looks for it in a specific order. This search process follows the LEGB Rule:

  1. Local Scope
  2. Enclosing Scope
  3. Global Scope
  4. Built-in Scope

If the name isn't found in any of these scopes, Python raises a NameError. 
Let's understand each scope.

1. Local Scope

Example:

def greet():
    message = "Hello"
    print(message)

greet()

Output:

Hello

The variable message exists only while the greet() function is running.

2. Enclosing Scope

An enclosing scope exists when one function is defined inside another function.

Example:

def outer():
    message = "Welcome"

    def inner():
        print(message)

    inner()

outer()

Output:

Welcome

The inner function can access variables from its enclosing function.

3. Global Scope

Variables declared outside all functions belong to the global scope.

Example:

language = "Python"

def show():
    print(language)

show()

Output:

Python

Global variables are accessible from most parts of your program unless shadowed by local variables.

4. Built-in Scope

Python includes many predefined names such as:

  • print
  • len
  • range
  • sum
  • max
  • min

Example:

numbers = [10, 20, 30]

print(len(numbers))

Example:

3

These built-in functions are always available without needing to define them yourself.

Understanding Variable Scope

A variable's scope determines where it can be accessed in your program. 

There are two primary scopes you'll work with regularly: 

Local Variables

Created inside a function and accessible only within that function.

def student():
    name = "Skill"
student()
print(name)

Output:

NameError: name 'name' is not defined

The variable name no longer exists after the function finishes executing.

Global Variables

Created outside all functions and accessible throughout the program.

Output:

Skill

Because name is global, the function can access it successfully.

Anatomy of a NameError Message

A typical error message looks like this:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    print(score)
NameError: name 'score' is not defined

Let's break it down:

  • Traceback: Shows the sequence of function calls leading to the error.
  • File: Indicates the file where the error occurred.
  • Line Number: Shows the exact line containing the problem.
  • Problematic Code: Displays the line that caused the error.
  • Exception Type: NameError.
  • Description: Explains which name Python couldn't find.

Learning to read tracebacks is an essential debugging skill and will save you time as your programs become more complex.

Common Causes of NameError in Python (With Examples and Fixes)

You have learnt what a NameError is and how Python searches for names using the LEGB rule. Now it's time to explore the most common reasons why this error occurs in real programs.

Understanding these causes will help you identify and fix NameError quickly.

1. Using a Variable Before Defining It

This is the most common reason for a NameError.

Incorrect Code

print(age)
age = 25

Output:

NameError: name 'age' is not defined

Why It Happens
Python executes code from top to bottom. When it reaches print(age), the variable age doesn't exist yet.

Correct Code

age = 25
print(age)

Output:

25

Tip: Always define variables before using them.

2. Typing the Variable Name Incorrectly

Even a small spelling mistake can cause a NameError.
Incorrect Code
username = "Alice"

print(userName)
Output
NameError: name 'userName' is not defined
Why It Happens
Python is case-sensitive.
  • username
  • userName
  • UserName
These are three different names.
Correct Code
username = "Alice"

print(username)
Output
Alice

3. Forgetting to Create the Variable

Sometimes we assume a variable exists when it hasn't been assigned a value.
Incorrect Code
total = price + tax
Output
NameError: name 'price' is not defined
Correct Code
price = 100
tax = 18

total = price + tax

print(total)
Output
118

4. Using a Variable Outside Its Scope

Variables created inside a function cannot be accessed outside that function.
Incorrect Code
def student():
    name = "Rahul"

student()

print(name)
Output
NameError: name 'name' is not defined
Why It Happens
The variable exists only inside the function.
Correct Code
def student():
    name = "Rahul"
    return name

print(student())
Output
Rahul

5. Misspelling a Function Name

Functions are also names.
Incorrect Code
def greet():
    print("Hello")

great()
Output
NameError: name 'great' is not defined
Correct Code
def greet():
    print("Hello")

greet()
Output
Hello

6. Forgetting to Import a Module

Python cannot use a module until it is imported.
Incorrect Code
print(math.sqrt(25))
Output
NameError: name 'math' is not defined
Correct Code
import math

print(math.sqrt(25))
Output
5.0

7. Misspelling a Module Name

Incorrect Code

import math

print(maths.sqrt(16))
Output
NameError: name 'maths' is not defined
Correct Code

import math

print(math.sqrt(16))
Output
4.0

8. Using Loop Variables Outside Their Intended Context

Sometimes developers accidentally use the wrong variable name after a loop.
Incorrect Code

for number in range(5):
    print(number)

print(numbers)
Output
NameError: name 'numbers' is not defined
Correct Code

for number in range(5):
    print(number)

print(number)

9. Calling a Class Before Defining It

Classes must be defined before creating objects.
Incorrect Code
student = Student()
Output
NameError: name 'Student' is not defined
Correct Code
class Student:
    pass

student = Student()

10. Using a Deleted Variable

After deleting a variable, it no longer exists.
Incorrect Code
city = "Delhi"

del city

print(city)
Output
NameError: name 'city' is not defined

11. Typing Built-in Function Names Incorrectly

Incorrect Code
pritn("Hello")
Output
NameError: name 'pritn' is not defined
Correct Code
print("Hello")

12. Forgetting Quotes Around Strings

Python thinks an unquoted word is a variable name.
Incorrect Code
print(Python)
Output
NameError: name 'Python' is not defined
Correct Code
print("Python")
Output
Python

13. Using a Variable Inside an Unexecuted Block

If the code that creates a variable never runs, the variable doesn't exist.
Incorrect Code
if False:
    score = 100

print(score)
Output
NameError: name 'score' is not defined
Correct Code
score = 0

if False:
    score = 100

print(score)

14. Using the Wrong Variable Name

Incorrect Code
marks = 95

print(score)
Output
NameError: name 'score' is not defined
Correct Code
marks = 95
print(marks)

15. Forgetting to Define Constants

Incorrect Code
area = PI * 10 * 10
Output
NameError: name 'PI' is not defined
Correct Code
PI = 3.14159

area = PI * 10 * 10

print(area)
Previous Post Next Post