Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Differences between `input` and `raw_input` [duplicate]

Tags:

python

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?

like image 767
Guillermo Siliceo Trueba Avatar asked Sep 27 '10 03:09

Guillermo Siliceo Trueba


People also ask

What is raw_input?

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? ")

What is the difference between eval and input in Python?

eval evaluates a piece of code. input gets a string from user input. Therefore: eval(input()) evaluates whatever the user enters.

What is raw_input () in Python give an example?

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.

Why is raw_input not defined in Python?

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.


1 Answers

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?

like image 183
aaronasterling Avatar answered Sep 18 '22 00:09

aaronasterling