Skip to content
Advertisement

Python name error in LInux terminal when the input is defined

I am running python 3.6 on Linux. When I use the python shell to test the code, it works as it is supposed to do. However, if run from the linux terminal, I get a name error.

#!/usr/bin/python
print("Hi")
name = input("What's your name?")
print (name, "is a cool name")

Then after inputting a name from the linux terminal, I get the following error:

Traceback (most recent call last):
  File "./test.py", line 3, in <module>
    name = input("What's your name?")
  File "<string>", line 1, in <module>
NameError: name 'Matt' is not defined

I know that if run on python 2, you need to use raw input, however this is not used in python 3. Is there another line of code so that the linux terminal accepts it, like #!/usr?

Advertisement

Answer

With the shebang line #!/usr/bin/python you are telling the system to use Python 2.

In Python 2, you would need to change input to raw_input, as follows:

#!/usr/bin/python
print("Hi")
name = raw_input("What's your name?")
print(name, "is a cool name")

See Greeting program for more information.

However, to tell the system to run the script with Python 3, change your shebang line to #!/usr/bin/python3, or preferably #!/usr/bin/env python3.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement