Kodewick
Lesson 6 of 31Contents

User input

Lesson 6 of 31 · Part 1 · Basics · about 15 minutes

So far every program has done the same thing each time. With input() a program can ask a question, wait for an answer, and use it. Press Run and type your own name; the page shows what happens when someone types Ada.

main.py
1name = input("What's your name? ")2print(f"Hello, {name}! Wick will light your lamp tonight.")
Output
What's your name? Ada
Hello, Ada! Wick will light your lamp tonight.

Asking a question

input() shows its prompt, waits until the user presses Enter, and gives back whatever they typed. Store that answer in a variable so you can use it later.

PieceWhat it does
input("Town? ")Shows Town? and waits for an answer
town = input(...)Keeps the answer in town
the promptOptional. End it with a space, or the answer sticks to it

Each input() asks one question. Two calls ask two questions, in order.

main.py
1town = input("Town name: ")2street = input("Street: ")3print("Delivering to", street, "street in", town)
Output
Town name: Lamplight
Street: north
Delivering to north street in Lamplight

Input is always text

Whatever the user types, input() gives back a string, even if it looks like a number. "7" is text, just as "seven" is.

Guess first

What does the second line print?

1lamps = "7"  # what input() gives when the user types 72print(lamps + lamps)

type() shows it plainly. Try to add a number and Python stops:

main.py
1lamps = input("How many lamps? ")2print(type(lamps))3print(lamps + 1)
Output
How many lamps? 7
<class 'str'>
Traceback (most recent call last):
  File "main.py", line 3, in <module>
    print(lamps + 1)
TypeError: can only concatenate str (not "int") to str

The TypeError says Python will not add a string and a number. It does not guess what you meant.

Turning text into numbers

You met int() and float() in lesson 2. Wrap input() in one of them and you get a number you can calculate with. Use int() for whole numbers and float() when the answer may have a decimal point.

main.py
1lamps = int(input("How many lamps? "))2hours = float(input("Hours each lamp burns: "))3print("Lamp-hours tonight:", lamps * hours)
Output
How many lamps? 7
Hours each lamp burns: 2.5
Lamp-hours tonight: 17.5

Tip: Read int(input("...")) from the inside out: first ask, then convert the answer.

When the answer isn't a number

Users type surprising things. int() only accepts text that looks like a whole number, so a word or a decimal makes it fail with a ValueError:

main.py
1lamps = int(input("How many lamps? "))2print("Lamps:", lamps)
Output
How many lamps? seven
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    lamps = int(input("How many lamps? "))
ValueError: invalid literal for int() with base 10: 'seven'

Before converting, a string method can spot the problem: .isdigit() gives True when every character is a digit, and False otherwise.

main.py
1print("42".isdigit())2print("seven".isdigit())3print("3.5".isdigit())4print("-4".isdigit())
Output
True
False
False
False

Notice the last two: a decimal point or a minus sign is not a digit. For now you can see the problem; in lesson 8, if lets your program act on it, and lesson 21 shows try and except, which catch the error itself.

Cleaning up input

People add spaces by accident and type in any mix of capitals. The string methods from lesson 5 tidy an answer before you use it. Chain them right after input():

main.py
1answer = input("Light the lamps? ").strip().lower()2print(f"[{answer}]")3print(answer == "yes")
Output
Light the lamps?   YeS
[yes]
True

The square brackets show that the spaces are gone. Cleaning first means "YES", " yes" and "Yes " all become the same "yes". (The == at the end compares two values; lesson 7 is all about it.)

Several values at once

Sometimes one answer holds several values, such as 3 4. .split() cuts it at the spaces, and you can catch the pieces in two variables at once. The pieces are still strings, so convert each one.

main.py
1size = input("Width and height: ")2w, h = size.split()3print("Area:", int(w) * int(h))
Output
Width and height: 3 4
Area: 12

a, b = ... needs exactly as many pieces as names. Type three numbers and Python reports a ValueError. What .split() really gives back is a list; lists get their own lesson, lesson 9.

A small calculator

Put it all together: ask for two numbers, convert them, and show some results with an f-string.

main.py
1a = float(input("First number: "))2b = float(input("Second number: "))3print(f"{a} + {b} = {a + b}")4print(f"{a} - {b} = {a - b}")5print(f"{a} * {b} = {a * b}")6print(f"{a} / {b} = {round(a / b, 2)}")
Output
First number: 17
Second number: 5
17.0 + 5.0 = 22.0
17.0 - 5.0 = 12.0
17.0 * 5.0 = 85.0
17.0 / 5.0 = 3.4

Run it again with your own numbers. Try 0 as the second number and see which line breaks.

Practice

Write the code, then press Check. A hint costs nothing; the answer is there when you need it. These exercises are checked without anyone typing, so the "answers" are already in variables; pretend they came from input().

Exercise 1

Double it

text holds what the user typed. Print the number doubled: 84.

It should print
84
exercise1.py
1text = "42"  # imagine this came from input()2print(text * 2)
Output
Press Run or Ctrl+Enter
Exercise 2

Tidy the answer

Clean up reply so the program prints yes with no spaces and no capitals.

It should print
yes
exercise2.py
1reply = "   YES "  # imagine this came from input()2print(reply)
Output
Press Run or Ctrl+Enter
Exercise 3

Shop total

line holds a price and an amount, separated by a space. Print Total: 7.5.

It should print
Total: 7.5
exercise3.py
1line = "2.5 3"  # imagine this came from input()2# Your code here
Output
Press Run or Ctrl+Enter

What you learned

  • input("prompt") shows the prompt, waits, and gives back what the user typed.
  • The answer is always a string. Convert it with int() or float() before doing math.
  • int() on text that isn't a whole number raises a ValueError; .isdigit() checks first for plain digits (no minus sign or decimal point).
  • Clean answers with .strip() and .lower() so different spellings match.
  • a, b = text.split() reads several values from one answer.