CodeRigor

LESSON

Read what the user types

Ask a question, read the line the user types, turn text into a number and build programs that prompt, read, compute and print.

So far every value was written into the program. A useful program asks the person running it for information and responds to what they type. The person running a program is called its user, and what they give the program is its input.

input() reads one line

The function input shows a message, waits for the user to type a line and press Enter, and gives that line back to your program. The message is called a prompt: it tells the user what to type.

Python
name = input("What is your name? ")
print(f"Hello, {name}!")

If the user types Ada, the whole conversation on the screen looks like this:

Text
What is your name? Ada
Hello, Ada!

Two details:

  • A function call can produce a value. input(...) produces the text the user typed, and the assignment gives that text the name name. Programmers say the function returns the text.
  • The prompt ends with a space, inside the quotation marks. Without it the user's typing would touch the question mark: What is your name?Ada.

Running programs that read input

This example has no Edit & run button, because a button cannot stop and wait for you to type. Run it in the Python playground instead:

  1. Copy the program into the editor.
  2. Open Standard input below the output and type what the user would type, one answer per line. For this program, type Ada.
  3. Press Run.

"Standard input" is the name programmers use for the stream of text that a program reads, which is normally the keyboard. On this site the program runs on our server, so you provide the typed lines in advance. Because nobody presses Enter on the screen there, the typed line is not shown in the output, and the reply follows the prompt on the same line: What is your name? Hello, Ada!. The program has still read Ada exactly as it would from a keyboard.

On your own computer, python3 hello.py behaves exactly as the conversation above shows: the program stops at each input and waits for you.

What input returns is always text

input always returns a string, even when the user types digits. That matters as soon as you calculate.

Python
answer = "36"
print(answer + answer)
print(answer * 2)

This prints 3636 twice. Between strings, + joins and * repeats. The string "36" is two characters, a 3 and a 6. It is not the number thirty-six.

Turn text into a number

The function int takes a string of digits and returns the integer it spells. The function float does the same for a number with a decimal point.

Python
answer = "36"
age = int(answer)
print(age + 1)
print(float("2.5") * 2)

This prints 37 and 5.0. Changing a value from one type to another is called converting it.

You can convert in the same statement that reads:

Python
age = int(input("How old are you? "))

Read that from the inside out: input returns the typed text, int converts it, and the assignment names the result age.

From typed text to a number you can calculate with
start / 4 ⇄ code
The user types the two characters 3 and 6. input returns them as the string "36". int converts that to the integer 36, and only then does + 1 mean arithmetic.
From typed text to a number you can calculate with
The user types the two characters 3 and 6. input returns them as the string "36". int converts that to the integer 36, and only then does + 1 mean arithmetic.
Python
answer = input("How old are you? ")
age = int(answer)
next_year = age + 1
print(f"Next year you will be {next_year}.")

The shape of an interactive program

Most small programs follow the same four steps: prompt, read, compute, print.

Prompt, read, compute, print
start / 4
Ask a question, read the answer as text, convert and calculate, then show the result. Longer programs repeat this shape.
Prompt, read, compute, print
Ask a question, read the answer as text, convert and calculate, then show the result. Longer programs repeat this shape.

Here is the whole shape in one program. It asks for the sides of a rectangle and prints its area.

Python
width = float(input("Width in metres: "))
height = float(input("Height in metres: "))
area = width * height
print(f"Area: {area:.2f} square metres")

With 2.5 and 4 typed as the two answers, it prints Area: 10.00 square metres. Try it in the playground with two lines of standard input.

Three errors you will meet

Forgetting to convert. This program reads an age and adds one to it:

Python
age = input("How old are you? ")
print(age + 1)
Text
Traceback (most recent call last):
  File "main.py", line 2, in <module>
    print(age + 1)
          ~~~~^~~
TypeError: can only concatenate str (not "int") to str

Read the last line first. age is a string, because input returned it, and Python will not add the integer 1 to a string. The line number points at the +, but the fix belongs one line earlier: age = int(input("How old are you? ")).

Text that is not a number. If the user answers ten to the corrected program, int cannot convert it:

Text
ValueError: invalid literal for int() with base 10: 'ten'

ValueError means a function was given a value it cannot use. The message quotes the text that failed, 'ten'. ("Base 10" is the ordinary way of writing numbers with the digits 0 to 9.) For now, assume the user types sensible numbers; later courses show how to ask again.

Reading more than was typed. On this site, a program that calls input when no typed lines are left stops with:

Text
EOFError: EOF when reading a line

EOF stands for "end of file": the input ran out. Either add another line to Standard input, or check that your program does not call input more times than it should.

What you can do now

You can prompt the user, read a line, convert it to a number and print a result that depends on what was typed. In the exercises you will predict what conversions produce, then write a program that holds a short conversation.

Next: make decisions, so that a program can respond differently to different answers.

Watch & read

Free lectures, talks and readings that cover this skill from another angle. All resources →

Starts at chapter 4, 'user input' (21:15), about ten minutes: input(), why the answer is text, and converting it with int() and float(). The chapter before it ('type casting', 16:05) covers the conversions on their own.