How To Define Raw_Input In Python 3

If you have been learning or working on Python 2, you might have come across the term raw_input() – a built-in function used to take user input. However, with the advent of Python 3, raw_input() has been replaced by another built-in function: input(). This tutorial will guide you on how to use input() to take user input in Python 3.

Step 1: Understand What Raw_Input() Did in Python 2

In Python 2, the raw_input() function is used to take input from the users in the form of a string. Here’s an example of how it looked in Python 2:

The above code would ask the user for their name, and then greet them with a customized message.

Step 2: Know the Difference Between Raw_Input() and Input() in Python 3

In Python 3, the raw_input() function does not exist anymore. Instead, it has been replaced by the input() function which serves a similar purpose. The input() function reads a line from the input, converts it to a string, and removes the trailing newline.

The main difference between raw_input() in Python 2 and input() in Python 3 is that Python 2 input() function reads an input (similar to raw_input()) and tries evaluating the input as a Python expression, potentially causing security issues.

Here’s an example of using the input() function in Python 3:

As you can see, the only change we made was replacing raw_input() with input(). The example would work the same way as it did in Python 2 by asking the user for their name and then greeting them with a customized message.

Step 3: Practice Using Input() in Python 3

In Python 3, all you need to do to take user input is use the input() function, followed by the user prompt message inside the parentheses. Let’s practice by writing a simple program that asks the user for their age and returns a message based on their input:

Here, the input() function takes user input as a string, and we convert it to an integer using the int() function, to later perform a comparison.

Full Code

Conclusion

In this tutorial, we discussed the differences between raw_input() in Python 2 and input() in Python 3, and how to define and use input() to accept user input. As Python 2 is no longer supported, it is crucial to familiarize yourself with the input() function for user input in Python 3.