raw_input python

In this post, we will learn about raw_input() function in Python.

raw_input() function is used to accept user input.It presents a prompt to the user , gets input from the user and returns the data input by the user in a string.

It is available in Python 2.x only, and is renamed to input() from Python 3.x version. Hence, in Python 3.x, we need to use input() function instead of raw_input().

If you would like to see how  python raw_input() works, ensure you have python 2 installed on your operating system.

Nonetheless, in this short article we’ll attempt to discuss on this subject so you wouldn’t be confused if you get to work with raw_input() in python 2.x code.

It is going to also assist you when you’re migrating your code from python 2 to python 3.

Python raw_input illustration

Here, we will start with  a simple python raw_input call.However, you ought to know at first that the raw_input() function requires string as input. Thus, we’ll now write code that will prompt for your profession and then prints it. The code is provided below.

python raw_input example

You can also save whatever response a user gives to the raw_input() call to a variable. Here I am saving the response to raw_input() to  a variable called prof.

python raw_input example 2

Note that , since this is Python 2 code, the print syntax is slightly different to what you use in Python 3. In Python 3, print is a function. Refer here for the differences between Python 2 and Python 3.

If you execute above code in Python 3, you will get this error.

To avoid this error, we need use input instead of raw_input in Python 3.

using input instead of raw_input in python 3

Let’s now try to enter an number as a response to raw_input, and see what happens.

So, even if you enter a number, raw_input() will interpret it as a string only.
How will you then convert it to a number then? Use int() function on the entered string. Let’s go through an example to calculate area of a square.
python raw_input example 3

That’s all for now on the raw_input function. Hope you’ve clearly understood the concept.




Recent Posts