This question already has an answer here:
In a tutorial, I read that that there is a difference between input
and raw_input
. I discovered that they changed the behavior of these functions in the Python 3.0. What is the new behavior?
And why in the python console interpreter this
x = input()
Sends an error but if I put it in a file.py and run it, it does not?
In python 2.x,
raw_input()
returns a string andinput()
evaluates the input in the execution context in which it is calledIn python 3.x,
input
has been scrapped and the function previously known asraw_input
is nowinput
. So you have to manually callcompile
and thaneval
if you want the old functionality.In 3.x, the above session goes like this
So you were probably getting an error at the interpretor because you weren't putting quotes around your input. This is necessary because it's evaluated. Where you getting a name error?
Its simple:
raw_input()
returns string valuesinput()
return integer valuesFor Example:
1.
Output:
2.
Output:
Hence if we perform
x + x =
It will output as 123123while if we perform
y + y =
It will output as 246input() vs raw_input()
raw_input collects the characters the user types and presents them as a string. input() doesn't just evaluate numbers but rather treats any input as Python code and tries to execute it. Knowledgeable but malicious user could type in a Python command that can even deleted a file. Stick to raw_input() and convert the string into the data type you need using Python's built in conversion functions.
Also input(), is not safe from user errors! It expects a valid Python expression as input; if the input is not syntactically valid, a SyntaxError will be raised.