NameError in Python: Causes and Fixes with Simple Examples
What is NameError in Python?
A NameError in Python occurs when you try to use a variable, function, or name that has not been defined.
In simple words, Python is saying:
“I don’t know what this name refers to.”
This error is very common for beginners and usually appears due to spelling mistakes, missing variable definitions, or incorrect scope.
Understanding Names in Python
In Python, every variable, function, or class must be defined before it is used.
Example:
x = 10
print(x)
If Python cannot find a name in memory, it raises a NameError.
Common NameError Message
A typical NameError message looks like this:
NameError: name 'x' is not defined
This message tells us:
-
Python tried to use
x -
xwas never defined -
Python cannot continue execution
Example 1: NameError Due to Undefined Variable
❌ Incorrect Code
print(total)
❌ Error
NameError: name 'total' is not defined
✔ Why this happens
-
The variable
totalwas never created -
Python cannot guess its value
✔ Correct Code
total = 100
print(total)
Example 2: NameError Due to Spelling Mistake
❌ Incorrect Code
number = 50
print(numbr)
❌ Error
NameError: name 'numbr' is not defined
✔ Why this happens
-
Variable name is misspelled
-
Python treats it as a different name
✔ Correct Code
number = 50
print(number)
Example 3: NameError with Function Call
❌ Incorrect Code
add(10, 20)
❌ Error
NameError: name 'add' is not defined
✔ Why this happens
-
Function
add()was never defined -
Python cannot execute it
✔ Correct Code
def add(a, b):
return a + b
print(add(10, 20))
Example 4: NameError Due to Variable Scope
❌ Incorrect Code
def show():
value = 10
print(value)
❌ Error
NameError: name 'value' is not defined
✔ Why this happens
-
valueis defined inside the function -
It is not accessible outside
✔ Correct Code
def show():
return 10
value = show()
print(value)
How to Debug NameError Easily
Use these simple techniques:
✔ Check spelling carefully
✔ Make sure variables are defined before use
✔ Print variable values
✔ Understand variable scope
Example:
print(globals())
How to Avoid NameError in Python
-
Always define variables before using them
-
Avoid spelling mistakes
-
Use meaningful variable names
-
Be careful with indentation and scope
-
Use an IDE with error highlighting
Summary
NameError in Python occurs when Python cannot find a name you are trying to use.
Once you understand how Python handles variable names and scope, fixing NameError becomes easy.
This error is very common while learning Python - keep practicing
❓ Frequently Asked Questions (FAQ)
Q1: Is NameError a syntax error?
No, it happens during program execution.
Q2: Can NameError stop my program?
Yes, unless fixed or handled.
Q3: Is NameError common for beginners?
Yes, extremely common.
📌 Final Tip
Always define variables and functions before using them in Python.
Comments
Post a Comment