How To Take String Input From Command Line In Python

Python provides developers with built-in functions that can be used to get input directly from users and interact with them using the command line (or shell as it is often called).

In Python 2, raw_input() and in Python 3, we use input() function to take input from Command line.

  1. Python 2 raw_input() function
  2. Python 3 input() function

String Input From Command Line In Python 2

If we execute the below code, program prompts the user for "Enter Your Name". Enter the name and the press "Enter" key on your keyboard. As we see below next statement "print(name)" is executed.

In [1]:
name = raw_input("Enter Your Name!")
print("printing name",name)
Enter Your Name!John
('printing name', 'John')

To prompt the input on the next line, add "\n" to raw_input() function as shown below.

In [2]:
name = raw_input("Enter Your Name!\n")
print("printing name",name)
Enter Your Name!
John
('printing name', 'John')

String Input From Command Line In Python 3

In [1]:
name = input("Enter Your Name!")
print("printing name",name)
Enter Your Name!John
printing name John