Python Program to Calculate Speed, Distance and Time
Beginner · Basics
Speed, distance and time are linked by one formula: speed = distance / time. Rearranged, it also gives distance = speed x time and time = distance / speed, and this program uses it all three ways.
Program
Speed = 150 km / 2.5 h = 60.0 km/h Distance = 60 km/h x 3 h = 180 km Time = 225 km / 90 km/h = 2.5 h, or 2 h 30 min
How it works
- Speed is distance divided by time, so 150 km in 2.5 hours is 60 km/h.
- Multiplying speed by time gives the distance covered: 60 km/h for 3 hours is 180 km.
- Dividing distance by speed gives the time taken: 225 km at 90 km/h is 2.5 hours.
int(hours)keeps the whole hours, and the leftover part times 60 gives the minutes, so 2.5 hours prints as 2 h 30 min.
Other ways to write it
One function that finds the missing value
speed = 60.00 km/h distance = 180.00 km time = 2.50 h
Keyword arguments with a default of None let you leave out whichever value is unknown, and the function works out that one.
Converting km/h to m/s
72 km/h = 20.0 m/s Shortcut: 72 x 5/18 = 20.0 m/s
Physics problems often need meters per second; multiplying by 1000 / 3600, which simplifies to 5/18, does the conversion.
Try it yourself
Find the average speed for a trip of 120 km in 2 hours followed by 180 km in 4 hours.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
All Python programs · CBSE class 12 practical file · Python exercises