Python Program to Convert Kilometers to Miles
Beginner · Basics
Kilometers and miles both measure distance: 1 kilometer is about 0.621371 miles, and 1 mile is about 1.609344 kilometers. This program converts a distance in kilometers to miles by multiplying by 0.621371.
Program
km_to_miles.py
km = 42.195 # the length of a marathon; or: km = float(input("Enter distance in km: "))
KM_TO_MILES = 0.621371 # 1 kilometer in miles
miles = km * KM_TO_MILES
print(f"{km} kilometers = {miles:.2f} miles")
Output
42.195 kilometers = 26.22 miles
How it works
- The conversion factor is stored in
KM_TO_MILES; capital letters are a Python habit for a value that never changes. - Multiplying the kilometers by the factor gives the distance in miles.
:.2frounds the answer to two decimal places, so a marathon comes out as 26.22 miles.
Other ways to write it
Miles to kilometers
Miles to kilometers
miles = 26.2
km = miles * 1.609344
print(f"{miles} miles = {km:.2f} kilometers")
Output
26.2 miles = 42.16 kilometers
To go the other way, multiply by 1.609344, or divide by 0.621371, which gives the same result.
A conversion table
A conversion table
print("Kilometers Miles")
for km in range(5, 51, 5):
print(f"{km:10} {km * 0.621371:5.2f}")
Output
Kilometers Miles
5 3.11
10 6.21
15 9.32
20 12.43
25 15.53
30 18.64
35 21.75
40 24.85
45 27.96
50 31.07range(5, 51, 5) counts from 5 to 50 in steps of 5, and the widths in the f-string, 10 and 5.2f, line up the columns.
Try it yourself
Add lines that also convert the distance to meters and to feet, using 1 mile = 5280 feet.
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