Python NameError: name 'string' is not defined


NameError: name 'string' is not defined

This is the common Python Error when you use the word string instead of the keyword str while type conversion or such in your program.

In this tutorial, we shall learn how to recreate this NameError and ways to handle this error.

Recreate NameError

Let us recreate this error.

Python Program

n = 100
s = string(n)

Output

Traceback (most recent call last):
  File "example1.py", line 2, in <module>
    s = string(n)
NameError: name 'string' is not defined

What we tried here is to convert a number to string.

But we all know that str(number) converts number to string but not string(number). This is kind of a typo error from the programmer point of view.

Solution to NameError

You have to use the correct Python keywords.

For example, let us correct the above Python program, by replacing the word -string with the correct keyword str.

Python Program

n = 100
s = str(n)

Summary

In this tutorial of Python Examples, we learned how to solve NameError in our Python programs.