Read Input from Command Line

To read input from command line in Python, we can use input() builtin function. input() function reads a string from standard input until a new line is entered, and returns the string. We can store the returned string into a variable.

The following is a simple code snippet to read a string into variable x.

x = input()

We can also print an optional prompt to standard output, so that the user can understand for what he is entering a string.

The following is a simple code snippet to read a string into variable x, with a prompt string 'Enter a string : '.

x = input('Enter a string : ')

Examples

ADVERTISEMENT

Read input from user

In the following example, we read input from user and store it as a string in variable x, using input(). We shall print it

Python Program

x = input()
print('You entered : ', x)

Output

Hello World
You entered :  Hello World

Read input from user with a prompt

We shall prompt the user to input his/her first name.

Python Program

x = input('Enter your first name : ')
print('Hello', x)

Output

Enter your first name : Arjun
Hello Arjun

Conclusion

In this Python Tutorial, we learned how to read input as a string from user, using input() function.