Python NameError: name 'string' is not defined
NameError: name 'string' is not defined
This is a common Python error that occurs when you mistakenly use the word string
instead of the correct keyword str
for type conversion or related operations in your program.
In this tutorial, we will learn how to recreate this error and understand the solution to handle it effectively.
Recreate NameError
Let us recreate this error to better understand how it occurs.
Python Program
n = 100
s = string(n)
Explanation:
- In this program, we attempt to convert a number
n
into a string usingstring(n)
. - However,
string
is not a built-in function or keyword in Python. The correct keyword for type conversion isstr
. - This results in a
NameError
because Python does not recognizestring
as a defined function.
Output
Traceback (most recent call last):
File "example1.py", line 2, in <module>
s = string(n)
NameError: name 'string' is not defined
In the output, Python shows that the name string
is not defined, triggering the NameError
.
Solution to NameError
To solve this error, you must use the correct built-in Python function. Instead of using string(n)
, we should use str(n)
to convert the number to a string.
Corrected Python Program
n = 100
s = str(n)
Explanation:
- In the corrected program, we replace
string(n)
withstr(n)
, which is the correct Python syntax for converting a number to a string. - The
str()
function works as intended, and there is no error when it is used.
Additional Examples of NameError
Here are a few more examples where the NameError
can occur, with explanations and solutions:
Example 1: Using an Undefined Variable
If you attempt to use a variable that has not been defined, you will get a NameError
.
Python Program
print(x)
Output
Traceback (most recent call last):
File "example2.py", line 1, in <module>
print(x)
NameError: name 'x' is not defined
Explanation:
- In this case, we are trying to print the value of a variable
x
that hasn't been defined. - To fix this, ensure that
x
is defined before using it.
Fixed Python Program
x = 10
print(x)
Example 2: Misspelling Built-in Functions
Another common cause of NameError
is misspelling a built-in function name.
Python Program
result = maxm(5, 10)
Output
Traceback (most recent call last):
File "example3.py", line 1, in <module>
result = maxm(5, 10)
NameError: name 'maxm' is not defined
Explanation:
- In this case, the user has misspelled the built-in function
max()
asmaxm()
. - To solve this, simply correct the function name to
max()
.
Fixed Python Program
result = max(5, 10)
Summary
In this tutorial, we have learned how to handle the NameError
in Python, specifically when the name 'string' is used incorrectly instead of the proper str
function. We also explored other common causes of NameError
, such as:
- Using undefined variables.
- Misspelling built-in function names.
Understanding and resolving NameError
helps in writing error-free Python programs.