NameError in Python
Python Errors & Solutions Master Series
Introduction
Learning Objectives
- 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?
Simple Example:
print(age)Output:
NameError: name 'age' is not definedWhy Does Python Raise a NameError?
For example:
name = "Coding Bihar"
print(name)Output:
Coding Bihar
print(age)
Output:
NameError: age 'age' is not definedSince 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:
- Local Scope
- Enclosing Scope
- Global Scope
- Built-in Scope
If the name isn't found in any of these scopes, Python raises a NameError.
1. Local Scope
Example:
def greet():
message = "Hello"
print(message)
greet()Output:
HelloThe 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:
WelcomeThe 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:
PythonGlobal 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:
- len
- range
- sum
- max
- min
Example:
numbers = [10, 20, 30]
print(len(numbers))Example:
3These 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 definedThe variable name no longer exists after the function finishes executing.
Global Variables
Created outside all functions and accessible throughout the program.
Output:
SkillBecause 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 definedLet'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 = 25Output:
NameError: name 'age' is not definedWhy 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:
252. 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