This question already has an answer here:
-
What's the difference between raw_input() and input() in python3.x?
6 answers
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 and input()
evaluates the input in the execution context in which it is called
>>> x = input()
\"hello\"
>>> y = input()
x + \" world\"
>>> y
\'hello world\'
In python 3.x, input
has been scrapped and the function previously known as raw_input
is now input
. So you have to manually call compile
and than eval
if you want the old functionality.
python2.x python3.x
raw_input() --------------> input()
input() -------------------> eval(input())
In 3.x, the above session goes like this
>>> x = eval(input())
\'hello\'
>>> y = eval(input())
x + \' world\'
>>> y
\'hello world\'
>>>
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?
input() 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.
Its simple:
raw_input()
returns string values
- while
input()
return integer values
For Example:
1.
x = raw_input(\"Enter some value = \")
print x
Output:
Enter some value = 123
\'123\'
2.
y = input(\"Enter some value = \")
print y
Output:
Enter some value = 123
123
Hence if we perform x + x =
It will output as 123123
while if we perform y + y =
It will output as 246