PythonMastery

Convert kilometres to miles in Python

Read a distance in kilometres, convert it to miles using 1 mile = 1.609344 km, and print a conversion table. Also shows miles to kilometres.

One mile is exactly 1.609344 kilometres. To convert kilometres to miles, divide by 1.609344.

The program

python
KM_PER_MILE = 1.609344

km = float(input("Distance in kilometres: "))
miles = km / KM_PER_MILE

print(f"{km} km = {miles:.2f} miles")

Typed in this example: 42.195. Press Run to type your own.

output
Distance in kilometres: 42.195
42.195 km = 26.22 miles

How it works

A conversion table

python
KM_PER_MILE = 1.609344

print(f"{'km':>5} {'miles':>8}")
for km in [1, 5, 10, 21.1, 42.2, 100]:
    print(f"{km:>5} {km / KM_PER_MILE:>8.2f}")
output
   km    miles
    1     0.62
    5     3.11
   10     6.21
 21.1    13.11
 42.2    26.22
  100    62.14

:>5 right-aligns a value in 5 characters, so the numbers line up in columns.

Miles to kilometres

For the other direction, multiply instead of dividing:

python
KM_PER_MILE = 1.609344

miles = 26.2
print(f"{miles} miles = {miles * KM_PER_MILE:.2f} km")
output
26.2 miles = 42.16 km

Learn the idea: Input & Output: Talking to Your User, F-Strings: Modern String Formatting