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 = "SkillDedication"
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:
25Tip: Always define variables before using them.
2. Typing the Variable Name Incorrectly
Even a small spelling mistake can cause a NameError.username = "Alice"
print(userName)
Output
NameError: name 'userName' is not defined
Why It Happens- username
- userName
- UserName
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.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
def student():
name = "Rahul"
student()
print(name)
Output
NameError: name 'name' is not defined
Why It Happensdef student():
name = "Rahul"
return name
print(student())
OutputRahul
5. Misspelling a Function Name
Functions are also names.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.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.
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.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.city = "Delhi"
del city
print(city)
Output
NameError: name 'city' is not defined
11. Typing Built-in Function Names Incorrectly
Incorrect Codepritn("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.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.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 Codemarks = 95
print(score)
Output
NameError: name 'score' is not defined
Correct Code
marks = 95
print(marks)
15. Forgetting to Define Constants
Incorrect Codearea = PI * 10 * 10
Output
NameError: name 'PI' is not defined
Correct Code
PI = 3.14159
area = PI * 10 * 10
print(area)
