The crew is planning a long drive to the test range. Everyone is asking the same question: how long will it take?
Rocket rubs his hands together. "I have an idea!" he says. "A calculator that asks for the distance and the speed, then works out the time. We have every piece we need."
Raven writes the pieces on the whiteboard: ask, convert, calculate, show. "What do you notice?" she asks. "It is four small steps, and we learned each one this week."
Nova hovers near the board. "And when a user types something unexpected," she says, "Python will tell us. Let's read that message calmly when it comes."
Rocket starts typing, one step at a time, testing as he goes.
# trip_time.py
# Works out how long a trip takes.
print("Trip time calculator")
distance = float(input("Distance in km: "))
speed = float(input("Speed in km per hour: "))
hours = distance / speed
minutes = hours * 60
print(f"The trip takes {hours:.2f} hours.")
print(f"That is about {round(minutes)} minutes.") round() rounds a number to the nearest whole number. Here is a run where the user types 150 and 60:
Trip time calculator Distance in km: 150 Speed in km per hour: 60 The trip takes 2.50 hours. That is about 150 minutes.
If the user types ten instead of 10, float() cannot turn the word into a number. The program stops with a ValueError, which means the value had the right type but could not be used.
Another common error is a TypeError, like trying to add a string and a number:
>>> float("ten")
Traceback (most recent call last):
File "<pyshell#0>", line 1, in <module>
ValueError: could not convert string to float: 'ten'
>>> "Fuel: " + 50
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
TypeError: can only concatenate str (not "int") to str Here is a second calculator with the same shape: ask, convert, calculate, show. Read it and predict before you run it.
# fuel_calc.py
distance = float(input("Distance in km: "))
rate = float(input("Fuel units per km: "))
fuel = distance * rate
print(f"Fuel needed: {fuel:.1f} units") Distance in km: 120 Fuel units per km: 0.75 Fuel needed: 90.0 units
| Statement | True or false? |
|---|---|
| A ValueError means a value could not be used, like the word ten for float(). | ? |
| "Score: " + 5 works fine in Python. | ? |
| round(2.6) gives 3. | ? |
| Most small programs get input, then calculate, then show output. | ? |
You built a real calculator from four small steps. In week 10 you will learn how to catch errors like ValueError so the program can ask again.