Python get input from user - error name not defined
Use raw_input()
instead, since you're using Python 2.7.
raw_input
gets the input as text (i.e. the characters that are typed), but it makes no attempt to translate them to anything else; i.e. it always returns a string.
input
gets the input value as text, but then attempts to automatically convert the value into a sensible data type; so if the user types ‘1’ then Python 2 input
will return the integer 1, and if the user types ‘2.3’ then Python 2 input
will return a floating point number approximately equal to 2.3
input
is generally considered unsafe; it is always far better for the developer to make decisions about how the data is interpreted/converted, rather than have some magic happen which the developer has zero control over.
It is the reason why that automatic conversion has been dropped in Python 3 - essentially; - raw_input
in Python 2 has been renamed to input in Python 3; and there is no equivalent to the Python 2 input
magic type conversion functionality.
NameError: name '' is not defined after user input in Python
Do not use input()
in 2.x. Use raw_input()
instead. Always.
Why do I get a NameError when using input()?
You are using Python 2 for which the input()
function tries to evaluate the expression entered. Because you enter a string, Python treats it as a name and tries to evaluate it. If there is no variable defined with that name you will get a NameError
exception.
To fix the problem, in Python 2, you can use raw_input()
. This returns the string entered by the user and does not attempt to evaluate it.
Note that if you were using Python 3, input()
behaves the same as raw_input()
does in Python 2.
Related Topics
Iterate Over All Pairs of Consecutive Items in a List
Filtering Pandas Dataframes on Dates
How to Make a Timezone Aware Datetime Object
Typeerror: Unsupported Operand Type(S) for -: 'Str' and 'Int'
What Do Ellipsis [...] Mean in a List
Pythonic Way to Print List Items
How to Return Two Values from a Function in Python
Why Is Button Parameter "Command" Executed When Declared
Permutations Between Two Lists of Unequal Length
What Is the Reason for Performing a Double Fork When Creating a Daemon