Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of input/raw_input in python 2 and 3 [duplicate]

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?

like image 814
218 Avatar asked Feb 12 '14 14:02

218


People also ask

What is the purpose of raw_input () function in Python?

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.

What is the difference between input () and raw_input () in Python?

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.

Can we use raw_input in Python 3?

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.

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.


1 Answers

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.

like image 91
Ashwini Chaudhary Avatar answered Oct 08 '22 22:10

Ashwini Chaudhary