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 = "Coding Bihar"

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

2. Typing the Variable
Name Incorrectly
Even a small spelling mistake can cause a NameError.

Incorrect Code

username = "Alice"

Output:

NameError: name 'userName' is not defined

Why It Happens

Loading...
Previous Post Next Post

Contact Form