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
KM_PER_MILEis written in capital letters to show that it is a constant: a value that never changes while the program runs.- 42.195 km (a marathon) divided by 1.609344 is 26.2187..., and
:.2frounds it to two decimal places. - You may see the factor 0.621371 in other programs. That is 1 / 1.609344, rounded, so
km * 0.621371gives almost the same answer.
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