2.10. Asking the user for input

Sometimes we would like to take the value for a variable from the user via their keyboard. Python provides a built-in function called input that gets input from the keyboard (in Python 2.0, this function was named raw_input). When this function is called, the program stops and waits for the user to type something. When the user presses Return or Enter, the program resumes and input returns what the user typed as a string.

Before getting input from the user, it is a good idea to print a prompt telling the user what to input. You can pass a string to input to be displayed to the user before pausing for input:

If you expect the user to type an integer, you can try to convert the return value to int using the int() function:

But if the user types something other than a string of digits, you get an error:

>>> prompt = 'What...is the airspeed velocity of an unladen swallow?\n'
>>> speed = input(prompt)
What...is the airspeed velocity of an unladen swallow?
What do you mean, an African or a European swallow?
>>> int(speed)
ValueError: invalid literal for int() with base 10:

Note

If you are typing Python code in interpreter you might want to add a new line using “\n” as shown above.

We will see how to handle this kind of error later.

Construct a block of code that asks the user for a number and prints three times that number. There is extra code to watch out for.

One limitation in Python is that you can’t add (concatenate) a number and a string. You must first convert the number to a string using the built-in str method.

You have attempted of activities on this page