Python - Read input from keyboard

Python

Share
python logo

In this tutorial we will learn about reading input from keyboard in Python.

How to read input?

In Python 2 we can read input from standard input device i.e. the keyboard using the following two built-in functions.

  • raw_input
  • input

In Python 3 we use the input function to read the user input from the standard input (keyboard).

The raw_input function

We use the raw_input function in Python 2 to read a line from standard input and return it as a string without the trailing new line.

In the following Python program we are asking the user to enter their name and then the code is printing a greetings message.

# take input
print("Enter your name:")

name = raw_input()

# output
print("Hello " + name + "!")

Here is a sample output.

$ python hello.py 
Enter your name:
Yusuf Shakeel
Hello Yusuf Shakeel!

We can even pass an optional string argument to the raw_input function which will be displayed before taking user input.

In the following Python program we are taking user input using the raw_input function. Note! We are passing a string to the raw_input function which asks the user to enter their name.

# take input
name = raw_input("Enter your name: ")

# output
print("Hello " + name + "!")

Here is a sample output.

$ python hello.py 
Enter your name: Yusuf Shakeel
Hello Yusuf Shakeel!

The input function

We use the input function in Python 3 to read user input from the standard input device the keyboard.

In the following Python program we are using the input function to take user input from the keyboard and saving the input in the name variable.

Note! It is assumed that the input string will be a valid value.

Next, we are using the print function to print the greeting message.

# ask user to enter name
print("Enter your name:")

# take user input
name = input()

# print out a greetings message
print("Hello %s!" %name)

Here is a sample output.

Enter your name: 
Yusuf Shakeel
Hello Yusuf Shakeel!

We can even pass a string as an argument to the input function.

The string argument represents a default message that is displayed before taking user input.

In the following Python program we are using the input function to take user input from the keyboard. We are passing a default string message to the input function as an argument.

# take user input
name = input("Enter your name: ")

# print out a greetings message
print("Hello %s!" %name)

Here is a sample output.

Enter your name: Yusuf Shakeel
Hello Yusuf Shakeel!
Share