Python – Getting User Input

Outside Resources:

TheNewBoston – raw input

Python for Beginners – input


You can ask the user for input as follows:

response = input('Say something: ')
print('You said this:')
print(response)

The input() function waits for the user to type some text and then returns that value. In this example, it stores that data in a variable called response.

The text in the parentheses of the input() function is the prompt. This text is printed on the screen so the user knows what to do.

Note: input() in Python 3 is the same as raw_input() in Python 2.

The input() function always returns a string, even if the user types a number.  Here is a demonstration of this:

a = input('Enter a number: ')
print(a * 5)
print(a + 3)

Output if you type “7”

Enter a number: 7
77777
Traceback (most recent call last):
  File "main.py", line 7, in 
    print(a + 3)
TypeError: can only concatenate str (not "int") to str

This is happening because “7” is a text string, and multiplying a string by 5 just causes it to repeat 5 times. You can’t add the int 3 to a string, so that part caused an error.

To fix this, convert the user input to int using the int() function:

a = input('Enter a number: ')
print(int(a) * 5)
print(int(a) + 3)

New Output:

a = input('Enter a number: ')
print(a * 5)
print(a + 3)