Python – Read String from Console

Read String from Console as Input using Python

To read a string from console as input to your Python program, you can use input() function.

input() can take an argument to print a message to the console, so that you can prompt the user and let him/her know what you are expecting.

In this tutorial, we will learn how to use input() function, to read an input from user in your console application.

Python - Read String from Console

Example 1: Read String from Console

In the following program, we shall prompt the user to enter his name. input() function does print the prompt message to console and waits for the user to enter input.

Python Program

#read string from user
firstName = input('Enter your first name: ')

print('Hello',firstName)

Output

Run the program. The prompt appears on the console. Type the string and click enter. The new line is considered end of the input and the execution continues with statements after input() statement in the program.

Enter your first name: Brooks
Hello Brooks

input() function returns what you have provided as input in the console and you can assign it to a variable. In the above program, we have assigned input() function to a variable. As a result, you can access the string value entered by the user using this variable.

Example 2: Read Strings from User through Console

In this program, we will read multiple strings from user through console, one by one. It is similar to our previous example, but it has two input() statements. The first input() statement shall read a string from console and assign it to firstName. The second input() statement shall read a string from console and assign it to lastName.

Python Program

#read multiple strings from user
firstName = input('Enter your first name: ')
lastName = input('Enter your last name: ')

print('Hello',firstName, lastName)

Output

Run the program, and you shall see the prompt by first input() statement. After you enter some string and type enter, you shall see the prompt by second input() statement. Enter a string for last name and click enter. The program has now read two strings from you, the user.

Enter your first name: Brooks
Enter your last name: Henry
Hello Brooks Henry

Summary

In this tutorial of Python Examples, we learned to read input from user, specifically to say, read string through console from user, using Python input(), with the help of well detailed Python example programs .