Python program to Convert Kilometers to Miles and Vice Versa

Let us begin with the fundamentals, namely understanding the significance of these measuring units. The units of length are the kilometer and the mile.

Examples:

1)km to miles

Input:

distance =6.5 km

Output:

The given distance 6.5 km in miles= 4.038905 miles

2)miles to km 

Input:

distance =6.5 miles

Output:

The given distance 6.5 miles in km= 10.460756071261889 km

Conversion of Kilometers to Miles and Vice Versa

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

1)Converting kilometers to miles

Formula :

1 kilometer = 0.62137 miles.

As a result, the value 0.62137 can be regarded as the conversion factor or ratio for the conversion to occur.

Algorithm:

  • Define a variable to store the value of the kilo-meter or allow user input.
  • Define and save the value of the conversion factor/ratio in a variable.
  • Create a variable to hold the value of a kilometre converted to a mile. Write the logic for converting kilometres to miles using conversion factor
  • Using the print() function, show the converted value.

Below is the implementation:

# given the distance in km
distkm = 6.5
# conversion ratio
conversion_ratio = 0.62137
# converting the km to miles
distmiles = distkm*conversion_ratio
# print the distance in miles
print("The given distance", distkm, "km", "in miles=", distmiles,"miles")

Output:

The given distance 6.5 km in miles= 4.038905 miles

2)Converting miles to kilometers

Formula :

1 mile= km / 0.62137

As a result, the value 0.62137 can be regarded as the conversion factor or ratio for the conversion to occur.

Algorithm:

  • Define a variable to store the value of the miles or allow user input.
  • Define and save the value of the conversion factor/ratio in a variable.
  • Create a variable to hold the value of a miles converted to a kilometer. Write the logic for converting miles to kilometer using conversion factor
  • Using the print() function, show the converted value.

Below is the implementation:

# given the distance in miles
distmiles = 6.5
# conversion ratio
conversion_ratio = 0.62137
# converting the miles to  km
distkm = distmiles/conversion_ratio
# print the distance in km
print("The given distance", distmiles, "miles", "in km=", distkm, "km")

Output:

The given distance 6.5 miles in km= 10.460756071261889 km

Related Programs: