Rocket wants a program that works out how many oxygen tanks a mission needs. Each crew member needs two tanks. He writes it, runs it, types 4, and the program says 44 tanks.
"Forty-four tanks for four people?" he says. "That would fill the whole launch pad."
Raven reads the code slowly. "What do you notice?" she asks. "The 4 came from the keyboard. Yesterday, keyboard text in quotes did strange things with plus and times."
Nova blinks. "Interesting," she says. "Ask the shell what type input gives you. I think you will find a clue."
Rocket types a test in the shell and sees the answer: str. Now he knows what to fix.
input("question") shows the question, waits for the user to type and press Enter, and gives back what they typed. It always gives back a string, even when the user types digits.
A string times a number repeats the string. So "4" * 2 is "44". That was the bug.
# tanks_bug.py (has a bug)
crew = input("How many crew members? ")
tanks = crew * 2
print("Oxygen tanks needed:", tanks) How many crew members? 4 Oxygen tanks needed: 44
int() turns a string of digits into a whole number. float() turns a string into a decimal number. Wrap input() inside one of them when you need a number.
# tanks.py
crew = int(input("How many crew members? "))
tanks = crew * 2
print("Oxygen tanks needed:", tanks) In the shell, the 4 after the question is what the user typed:
How many crew members? 4 Oxygen tanks needed: 8
Programs often ask more than one question. Convert each answer as soon as you get it, so every variable already holds the right type.
# supplies.py
crew = int(input("Crew size: "))
days = int(input("Days on the mission: "))
bottles = crew * days * 3
print("Water bottles to pack:", bottles) | Statement | True or false? |
|---|---|
| input() gives back a string even if the user types 42. | ? |
| int(input("Crew size: ")) gives back a whole number. | ? |
| float() turns the string "2.5" into the number 2.5. | ? |
| You only need int() on the last question a program asks. | ? |
Your programs can now ask questions and use the answers. Tomorrow you will build neat, readable messages with f-strings.