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?
The function raw_input() presents a prompt to the user (the optional arg of raw_input([arg])), gets input from the user and returns the data input by the user in a string. For example, name = raw_input("What is your name? ")
eval evaluates a piece of code. input gets a string from user input. Therefore: eval(input()) evaluates whatever the user enters.
a = input() will take the user input and put it in the correct type. Eg: if user types 5 then the value in a is integer 5. a = raw_input() will take the user input and put it as a string. Eg: if user types 5 then the value in a is string '5' and not an integer.
Because we are using Python 3. x to run our program, raw_input() does not exist. Both the raw_input() and input() statements are functionally the same. This means we do not need to make any further changes to our code to make our codebase compatible with Python 3.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With