Use of input/raw_input in python 2 and 3

218 picture 218 · Feb 12, 2014 · Viewed 25k times · Source

I would like to set a user prompt with the following question:

save_flag is not set to 1; data will not be saved. Press enter to continue.

input() works in python3 but not python2. raw_input() works in python2 but not python3. Is there a way to do this so that the code is compatible with both python 2 and python 3?

Answer

Ashwini Chaudhary picture Ashwini Chaudhary · Feb 12, 2014

Bind raw_input to input in Python 2:

try:
    input = raw_input
except NameError:
    pass

Now input will return a string in Python 2 as well.


If you're using six to write 2/3 compatible code then six.input() there points to raw_input() in Python 2 and input() in Python 3.