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?
Python raw_input function is used to get the values from the user. We call this function to tell the program to stop and wait for the user to input the values. It is a built-in function. The input function is used only in Python 2.
There are two functions that can be used to read data or input from the user in python: raw_input() and input(). The results can be stored into a variable. raw_input() – It reads the input or command and returns a string. input() – Reads the input and returns a python type like list, tuple, int, etc.
The raw_input() function reads a line from input (i.e. the user) and returns a string by stripping a trailing newline. This page shows some common and useful raw_input() examples for new users. Please note that raw_input() was renamed to input() in Python version 3.
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.
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.
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