Solved – NameError: name ‘X’ is not defined in Python

NameError: name ‘X’ is not defined is an error which happens when you confuse Python versions.

In this article I am going to explain what happens when you get this error and how you can solve it with a main solution, we will also explore other solutions which can possibly solve the issue.

Describing NameError: name ‘X’ is not defined

First of all, let us try to reproduce the error.

Let us run the script bellow.

                                                                       #
vari = input("actor name: ")
print("actor name is" + vari)
                                                                       #

This is the error message, as you can see bellow Python says our input aegon is not defined.

                                                                        #
line 1, in <module>
 vari = input("actor name: ")
 File "<string>", line 1, in <module>
 NameError: name 'aegon' is not defined
                                                                       #

To solve the problem above, I have 2 solutions which worked for me, bellow is a detailed explanation of both.

Solution 1 : use raw_input

First of all, you need to understand that this error happens in Python 2, check if you really have Python 3, most of the time you are not, you are using Python 2 syntax in Python 3 and there is no compatibility.

input does not work in Python 2 only  raw_input works.

Replace the code bellow which contains input

                                                                       #
vari = input ("actor name: ")
print ("actor name is" + vari)
                                                                       #

With a code which uses raw_input.

                                                                       #
vari = raw_input ("actor name: ")
print ("actor name is" + vari)
                                                                       #

Solution 2 : use the six library

Another solution is to use the six library in order to import input

The Six library is a Python 2 and 3 Compatibility Library.

Six provides simple utilities for wrapping over differences between Python 2 and Python 3. It is intended to support codebases that work on both Python 2 and 3 without modification.

This is a link to the six library’s documentation : https://six.readthedocs.io

After installing the library, you can just use input like you did before and no error should occur.

Summing-up

This is the end of the article, the error nameerror: name x is not defined could be confusing but with a little bit of investigating the error could be solved, thanks for reading our post and good luck with the scripts to come.

If you want to support us consider donating to our Kofi account using the red button on top of this page. Keep coding, keep learning Python and cheers.

If you want to learn more about Python, please check out the Python Documentation : https://docs.python.org/3/