Editor

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_distance_time.py
# 1. Speed from distance and time
distance = 150 # in km; or: distance = float(input("Enter distance in km: "))
hours = 2.5 # in hours; or: hours = float(input("Enter time in hours: "))
speed = distance / hours
print(f"Speed = {distance} km / {hours} h = {speed} km/h")
# 2. Distance from speed and time
speed = 60 # km/h
hours = 3
print(f"Distance = {speed} km/h x {hours} h = {speed * hours} km")
# 3. Time from distance and speed
distance = 225 # km
speed = 90 # km/h
hours = distance / speed
whole_hours = int(hours)
minutes = round((hours - whole_hours) * 60)
print(f"Time = {distance} km / {speed} km/h = {hours} h, or {whole_hours} h {minutes} min")
Output
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

  1. Speed is distance divided by time, so 150 km in 2.5 hours is 60 km/h.
  2. Multiplying speed by time gives the distance covered: 60 km/h for 3 hours is 180 km.
  3. Dividing distance by speed gives the time taken: 225 km at 90 km/h is 2.5 hours.
  4. 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

One function that finds the missing value
def solve(speed=None, distance=None, hours=None):
if speed is None:
return f"speed = {distance / hours:.2f} km/h"
if distance is None:
return f"distance = {speed * hours:.2f} km"
return f"time = {distance / speed:.2f} h"
print(solve(distance=150, hours=2.5))
print(solve(speed=60, hours=3))
print(solve(speed=90, distance=225))
Output
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

Converting km/h to m/s
speed_kmh = 72
speed_ms = speed_kmh * 1000 / 3600 # 1 km = 1000 m, 1 h = 3600 s
print(f"{speed_kmh} km/h = {speed_ms} m/s")
print(f"Shortcut: {speed_kmh} x 5/18 = {speed_kmh * 5 / 18} m/s")
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises