User input
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.
1name = input("What's your name? ")2print(f"Hello, {name}! Wick will light your lamp tonight.")
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.
| Piece | What it does |
|---|---|
input("Town? ") | Shows Town? and waits for an answer |
town = input(...) | Keeps the answer in town |
| the prompt | Optional. End it with a space, or the answer sticks to it |
Each input() asks one question. Two calls ask two questions, in order.
1town = input("Town name: ")2street = input("Street: ")3print("Delivering to", street, "street in", town)
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.
What does the second line print?
1lamps = "7" # what input() gives when the user types 72print(lamps + lamps)
lamps holds the string "7", and + on two strings joins them. So you get 77, not 14.
type() shows it plainly. Try to add a number and Python stops:
1lamps = input("How many lamps? ")2print(type(lamps))3print(lamps + 1)
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 strThe 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.
1lamps = int(input("How many lamps? "))2hours = float(input("Hours each lamp burns: "))3print("Lamp-hours tonight:", lamps * hours)
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:
1lamps = int(input("How many lamps? "))2print("Lamps:", lamps)
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.
1print("42".isdigit())2print("seven".isdigit())3print("3.5".isdigit())4print("-4".isdigit())
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():
1answer = input("Light the lamps? ").strip().lower()2print(f"[{answer}]")3print(answer == "yes")
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.
1size = input("Width and height: ")2w, h = size.split()3print("Area:", int(w) * int(h))
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.
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)}")
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().
Double it
✓text holds what the user typed. Print the number doubled: 84.
84
1text = "42" # imagine this came from input()2print(text * 2)
Tidy the answer
✓Clean up reply so the program prints yes with no spaces and no capitals.
yes
1reply = " YES " # imagine this came from input()2print(reply)
Shop total
✓line holds a price and an amount, separated by a space. Print Total: 7.5.
Total: 7.5
1line = "2.5 3" # imagine this came from input()2# Your code here
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()orfloat()before doing math. int()on text that isn't a whole number raises aValueError;.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.