Progress

Python Program to Convert Kilometer (km) to Miles

Python Program to Convert Kilometer (km) to Miles

Problem Statement: Write a Python program to convert distance from Kilometer (km) to Miles and from Miles to Kilometers (km).

Description: Kilometer and Miles are the two most used units for distance measurement which are used commonly. Here is the formula to convert them.

Formula to convert km to Miles:

Mile = Kilometer*0.6215

Formula to convert Miles to km.

Kilometer = Mile*1.609

It is easy to write the Python program to convert kilometer km to miles and vice versa when the formula is known.

It is recommended to try the solution on yourself and submit it in comments.

Python Program: Kilometer (km) to Miles

Copy
#Km to Mile 1km = 0.6214Mile

km = float(input("Enter the distance in km: "))
mile = km*0.6215
print("{0} km = {1:.2f} Miles".format(km, mile))
Output
Enter the distance in km: 5
5.0 km = 3.11 Miles

The Python program is based on the formula we described above.

We take the input and convert it to float type to preserve decimal points. Then we convert the distance in Kilometers (km) to Miles.

At last, we print the result using the string format() method.

The code {1:.2f} means the second argument (index 1) of format() method and round off to 2 decimal points.

Python Program: Miles to Kilometres (km)

Copy
#Mile to km 1Mile = 1.609km

mile = float(input("Enter the distance in Miles: "))
km = mile*1.609
print("{0} Miles = {1:.2f} km".format(mile, km))
Output
Enter the distance in Miles: 5
5.0 Miles = 8.04 km

This is also the same Program as above only the formula is change to convert Miles to KIlometers (km).

Related Python Examples:

Share the Post ;)

Related Posts