Asking for input

Getting Started, lesson 5 of 5

👋 Getting Started, lesson 5 of 5

Asking for input

Make programs interactive with input() and convert text to numbers.

10 min

1 exercise

2 quizzes

0/3 solved

Getting Python ready… examples can run in a moment.

input() pauses the program and waits for the user to type something. Whatever they type is returned, so you usually store it in a variable. The text inside the parentheses is the prompt shown to the user.

Example

Say hello

One line per input() call

The Input box supplies what the user types (one line per input()). Change it and run again. If the program asks for more lines than the box has, input() stops with an EOFError.

Important: input() always gives you a string, even if the user types digits. Adding two strings glues them together, so "7" + "5" is "75"!

To do math, convert the text first:

  • int(text) turns "7" into the whole number 7
  • float(text) turns "2.5" into the decimal 2.5
Example

Text vs. numbers

One line per input() call

Try other numbers in the Input box (one per line).

Walkthrough

Text or number?

valuetypeaba + bint(a) + int(b)"7"str
Step 1 of 4

The user types 7, but input() hands back the text "7", a str.

just worked out
glued text
real addition

The values from the example when the user types 7 and then 5. Quotes mean the value is a string.

Quiz

What does this print?

Exercise

Double it

The program reads a number as text. Convert it to an int, store it in a variable called number, then print double the number.

When the user types 21, it should print 42.

Your program receives this input: 21

Example

Mini program: pizza planner

One line per input() call

int(input(...)) reads and converts in one step. Change the 3 to plan a hungrier party.

Quiz

The user types 5 when x = input() runs. What type is x?