Skip to main content

User Input

Your programs can get information from the person using them.

In other words, you can ask the user to type something in.

When Python reaches the input() function it pauses, and it carries on only after the user has entered something.

The next example asks for a name and, once you type one, shows it on the screen:

Example

Asking the user for input:

Prompt
Write a Python program that asks for user input. Print "Enter your name:", read input, and greet the user.
Output: complete Python program

Using prompt

Above, the name had to be typed on a new line. The input() function also takes a prompt parameter: a message shown just before the place where the user types, on the same line:

Example

Show a message in front of the input:

Prompt
Write a Python program that uses input() with a prompt parameter. Use "Enter your name:" as the prompt and greet the user.
Output: complete Python program

Multiple Inputs

A program can ask for input as many times as you like. At each request, Python pauses until the user responds:

Example

Asking for several inputs:

Prompt
Write a Python program with multiple input() calls. Ask for name, favorite animal, color, and number, then combine them.
Output: complete Python program

Input Number

Whatever the user types arrives as a string. That applies to numbers too, as with the favorite number in the example above: the interpreter still sees a string.

To get a real number, pass the input to the float() function:

Example

Calculating a square root needs a number, so the input is converted first:

Prompt
Write a Python program that converts user input to a number. Ask for a number, convert with float(), and calculate its square root.
Output: complete Python program

Validate Input

Checking what the user typed is good practice. In the example above, typing anything other than a number causes an error.

We can prevent that by testing the input first. When it isn't a number, the user can see a message such as "Wrong input, please try again" and get another chance:

Example

Repeat the question until the user enters a number:

Prompt
Write a Python program that validates user input. Keep asking until the user enters a valid number using a while loop and try/except.
Output: complete Python program