[Tutor] Help with NameError

Peter Otten __peter__ at web.de
Thu Sep 1 05:39:59 EDT 2016


Bryan Callow wrote:

> Could someone help me with a NameError that I can't seem to figure out.
> The program asks for an input and then runs two DC motors.  It worked for
> a while and then when I reopened the program today I keep getting this
> error.  Thank you.  -Bryan

[...]
> print('Which direction would you like to move?')
> direction = input("Type 'f' for forward, 'b' for backward, or 'e' to exit:
> ")
> while direction not in exit_:
[...]

My crystal ball says:

Your script is written in Python 3, but you are trying to run it with Python 
2. 

Background: Python 2's input() function evaluates user input as a Python 
expression -- if for example you enter 1+1 input() will return 2; if you 
enter b input() will look up the variable b and fail with a NameError 
because no such variable exists. 

Run your script with 

$ python3 yourscript.py

and everything should work as expected. To avoid such confusion in the 
future you can insert

#!/usr/bin/env python3

as the first line, make the script executable with

$ chmod u+x yourscript.py

and run it with

$ ./yourscript.py



More information about the Tutor mailing list