raw_input in Python 3

Hemank Mehtani Oct 10, 2023
raw_input in Python 3

The raw_input() function can read a line from the user. This function will return a string by stripping a trailing newline. It was renamed to input() function in Python version 3.0 and above.

The basic difference between raw_input and input is that raw_input always returns a string value while input function does not necessarily return a string, as when the input by the user is in numbers, it will take it as an integer.

Sometimes, there can be some exceptions raised while getting input from the user.

The try and except statement is used to handle these kinds of errors within our code in Python. The code block inside the try block is used to check some code for errors.

For example,

try:
    input = raw_input
except NameError:
    pass
print("Welcome to this " + input("Say something: "))

Output:

Say something: tutorial
Welcome to this tutorial

The six provides simple utilities for wrapping differences between any version of Python 2 and any version of Python 3.

It is intended to support code that works on both Python 2 and 3 without any modification.

For example,

from six.moves import input as raw_input

val1 = raw_input("Enter the name: ")
print(type(val1))
print(val1)

val2 = raw_input("Enter the number: ")
print(type(val2))
val2 = int(val2)
print(type(val2))
print(val2)

Output:

Enter the name: Hemank 
<class 'str'>
Hemank 
Enter the number: 17
<class 'str'>
<class 'int'>
17

Note that you have to implement six in the first line of code.

Related Article - Python Input