Last modified: Feb 23, 2025 By Alexander Williams
Fix Python NameError: Name 'True' Not Defined
Python is a powerful programming language. But beginners often face errors. One common error is NameError: Name 'True' is Not Defined.
This error occurs when Python cannot find the name True
in the code. It usually happens due to typos or incorrect usage.
What Causes the NameError?
The NameError occurs when Python encounters an undefined name. For example, if you write true
instead of True
, Python will raise this error.
Python is case-sensitive. So, True
and true
are different. Always use the correct case for Python keywords.
Example of NameError: Name 'True' Not Defined
Here is an example that causes the error:
# Incorrect code
if true:
print("This is true")
Running this code will result in the following error:
NameError: name 'true' is not defined
The error occurs because true
is not defined. Python expects True
for boolean values.
How to Fix the NameError
To fix the error, ensure you use the correct keyword. Replace true
with True
.
# Corrected code
if True:
print("This is true")
Now, the code will run without errors. The output will be:
This is true
Always double-check your code for typos. This simple step can save you time debugging.
Common Scenarios Leading to NameError
Here are some common scenarios where this error might occur:
- Using lowercase
true
instead ofTrue
. - Misspelling
True
asTure
orTru
. - Using
True
in a scope where it is not defined.
For more details on handling such errors, check out our guide on Why Does NameError Occur in Python?.
Using Try-Except Blocks to Handle NameError
You can use try-except
blocks to handle NameError gracefully. This is useful in larger programs.
try:
if true:
print("This is true")
except NameError:
print("NameError: 'true' is not defined. Did you mean 'True'?")
This will catch the error and print a helpful message. Learn more about Handling NameError in Python Try-Except Blocks.
Conclusion
The NameError: Name 'True' is Not Defined is a common issue for beginners. It happens due to typos or incorrect usage of Python keywords.
Always use the correct case for Python keywords like True
, False
, and None
. Double-check your code to avoid such errors.
For more tips on debugging Python errors, visit our guide on How to Fix NameError in Python.