It’s easy to convert kilometers to miles or miles to kilometers in Python. The kilometer is the unit of length in the metric system. However, sometimes length is also expressed in miles. Converting from one unit to another is simple. The conversion ratio is as follows.
- 1 kilometer is equal to 0.62137 miles.
- 1 mile is equal to 1.60934 kilometer.
Using this information you can easily convert one unit into another.
How about a Python program that does the conversion for us.
In this tutorial, we will see how can we create a Python program that converts kilometers to miles and vice versa.
The program will take user from the input and provide the output in the converted unit.
Table of Contents
Convert Kilometers to Miles in Python
In this code, we will take the distance in Kilometers from the user and then we will multiply it with the conversion ratio. After multiplying we will get the distance in miles. This value obtained after multiplying is then printed to the screen.
The code is as follows:
#convert kilometers into miles km = float(input("Enter distance in kilometers: ")) # conversion factor conv_fac = 0.621371 # calculate miles miles = km * conv_fac print('%0.3f kilometers is equal to %0.3f miles' %(km,miles))
Note that in the code we have accepted the input as float.
Convert Miles to Kilometers in Python
In this code, we will take the distance in miles from the user and then we will multiply it with the conversion ratio. After multiplying we will get the distance in kilometers. This value obtained after multiplying is then printed to the screen.
The code to covert miles into kilometers is as follows :
#convert miles into kilometers miles = float(input("Enter distance in miles: ")) # conversion factor conv_fac = 1.60934 # calculate miles km = miles * conv_fac print('%0.3f miles is equal to %0.3f Kilometers' %(miles,km))
The output obtained after running the code above is :
This tutorial was about how to write a program in Python that converts miles into kilometers and kilometers into miles. If you’re interested in more tutorials, have a look at how to create a Python script to download Youtube videos.