Reading Raw Input

In Python, we can read a line of input from stdin using the following syntax:

Python 2 syntax

# read a line from STDIN
my_string = raw_input()

Python 3 syntax

# read a line from STDIN
my_string = input()

Here our variable contains the input line as string.

If we then want to print the contents of whatever we saved to , we write the following:

print(my_string)

In Python, we can also print a prompt and read a line of input from stdin using the following syntax:

Python 2 syntax

name = raw_input("Hey, what's your name?\n")

Python 3 syntax

name = input("Hey, what's your name?\n")

Both lines of code above print the following prompt message to stdout:

Hey, what's your name?

The program then pauses, waiting for input from the keyboard (the program will be blocked from continued execution until it reads an enter/return key or some other terminator). When a line of input is entered, that string of text is saved to the variable. Similarly, you can read a line of input from stdin without passing any string arguments to raw_input or input.

If we then want to print the contents of whatever we saved to , we write the following:

print(name)