We will learn what is
NameError and how to fix it. We will also learn how to fix the
NameError: name 'python' is not defined when we call Python inside the interpreter instead of the terminal in Python.
NameError: name 'python' is not defined in Python
Sometimes we encounter a
NameError in Python because we have written a variable in our code, but we have not told Python what that variable is.
Now we have written a Python script to demonstrate how to raise the error.
name="Bob" fave_animal="dog" print("Hi",name,"Your favorite animal is a",fave_animal) print("Your favorite film is", film)
In this code, we have defined
fave_animal but have not defined
film, so when we run this, we get
name 'film' is not defined error. It means Python does not know what
NameError: name 'film' is not defined
We can fix this by defining
film, and we can do that by running this script.
film="John Wick" print("Your favorite film is", film)
Your favorite film is John Wick
Another reason you might get the error is when you unintentionally wrote the variable wrong like:
films, so if we run this, it will raise the same error.
film="John Wick" print("Your favorite film is", films)
NameError: name 'films' is not defined
Another way of getting the error is supposing you forgot to put a word inside the quotation when you defined a string anywhere. In our case, we are doing a silly mistake in our Python script, and if we run this code, we get the same error.
NameError: name 'Your' is not defined
Most beginners make these types of mistakes and sometimes find it hard to find a solution.
One more thing that beginners make this silly mistake is they try to call
python inside the Python interpreter, and when they execute this command inside the interpreter, they get the same error we discussed.
C:\Users\Dell>python Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec 7 2020, 17:08:21) [MSC v.1927 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> python Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'python' is not defined
When we run the CMD and type
python, it starts the Python interpreter but typing it again tries to interpret
python as a variable name and that name is not defined, so we get the error.
In CMD, you don’t need to call it again to start Python. The Python interpreter has already started, so there is no need to call
python to start.