Reading Keyboard Input in Python



Reading keyboard input in Python can be easily done by using the built-in functions. Python provides two built-in functions to read a line of text from standard input, which by default comes from the keyboard. These functions are:

  • raw_input()
  • input()

Using the raw_input() Function

The Python raw_input() function reads keyboard input and returns it as a string (removing the trailing newline). It is important to note that this function is available for the Python 2.x version only. It was renamed to input() in the Python 3.x versions.

Example

Let's take an example of using the raw_input() function in the Python 2.7.17 version for reading keyboard input.

# Read the keyboard input
input_data = raw_input("Enter your input: ")

# Display the output
print"Received input is : ", input_data

While executing the above program ,it prompts you to enter any input and it would display same as string on the screen. When I typed "Hello Python!", its output is like this ?

Enter your input: Hello Python
Received input is : Hello Python

Using the input() Function

The input() function is equivalent to the raw_input() function from the Python older version. This function accepts any type of data from the keyboard and returns it as Python string. The function allows us to provide a prompt text for the user, which will appear on the standard output before the cursor when you run the code.

Example

The following example demonstrates reading keyboard input in Python using the input() function.

# Read the keyboard input
input_data = input("Enter your input: ")

# Display the output
print("Received input is : ", input_data)

When we run above program, it produces following result ?

Enter your input: Hello Python
Received input is : Hello Python

Reading Numerical Input from Keyboard

As we know that, the input() function converts the any type of standard input to string, we need to explicitly convert it to the desired data type by using the conversion functions like int(), or float().

Example

The following example demonstrates how read the numerical keyboard input in Python using the input() function.

# Read the numerical input from keyboard
int_data = int(input("Enter any integer value: "))
float_data = float(input("Enter any float value: "))

# Display the output
print("Received integer input is : ", int_data)
print("Received float input is : ", float_data)

print(f"The sum of {int_data} and {float_data} is {int_data+float_data}") 

On executing the above program, you will get the following result:

Enter any integer value: 20
Enter any float value: 5.2
Received integer input is :  20
Received float input is :  5.2
The sum of 20 and 5.2 is 25.2
Updated on: 2025-09-01T11:30:40+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements