This question already has an answer here:
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?
Bind
raw_input
toinput
in Python 2:Now
input
will return a string in Python 2 as well.If you're using
six
to write 2/3 compatible code thensix.input()
there points toraw_input()
in Python 2 andinput()
in Python 3.You can write your code in either python2 and use futurize or in python3 and use pasteurize. This removes the complexity of thinking about compatible code and guarantees good practices.
Regarding this specific question
Is exactly what the above scripts produce.
I think the best way to do this is
...it'll work across 2 and 3.
Explicitly load the function:
from builtins import input
Then you can use
input()
in python2 as well as python3.You may have to install the dependency:
pip install future
Update: This method only works if you have future installed and the answers above are much better and more generalizable.
From this cheatsheet there is another method that looks cleaner:
This is because, In python 2,
raw_input()
accepts everything given to stdin, as a string, where asinput()
preserves the data type of the given argument (i.e. if the given argument is of typeint
, then it will remain asint
only, but won't be converted tostring
as in case ofraw_input()
). That is basically, wheninput()
is used, it takes the arguments provided in stdin as string, and evaluates the same. And this evaluation converts the argument to corresponding type.Therefore, while using
input()
in Python 2, user has to be careful while passing the arguments. If you are passing a string, you need to pass it with quote ( since python recognizes characters inside quote as string). ElseNameError
will be thrown.Whereas, if using
raw_input()
, you need not worry about the data type while passing the argument as everything it accepts as a string. But yes, inside your code you need to take care of appropriate type conversion.To avoid this extra care needed for
input()
in Python 2, it has been removed in Python 3. Andraw_input()
has been renamed toinput()
in Python 3. The functionality ofinput()
from Python 2 is no more in Python 3.input()
in Python 3 serves whatraw_input()
was serving in Python 2.This post might be helpful for a detailed understanding.