In this post, we will learn how to convert kilometers to miles using Python Programming language.
This program asks the user to enter the distance in kilometers then, it converts the distance into miles by multiplying the entered value with 0.621371.
We will use the following methods for the conversion.
- Using Standard Method
- Using User-defined Function
So, without further ado, let’s begin this tutorial.
Python Program to Convert Kilometers to Miles
# Python Program to Convert Kilometers to Miles km = float(input("Enter the distance in kilometers: ")) # Conversion factor fact = 0.621371 # Converting kilometers to miles miles = km * fact # Display output print("%.2f kilometers is equal to %.2f miles" %(km, miles))
Output
Enter the distance in kilometers: 3
3.00 kilometers is equal to 1.86 miles
How Does This Program Work ?
km = float(input("Enter the distance in kilometers: "))
The user is asked to enter the distance in kilometers.
We have defined a constant named fact which contains the conversion factor.
# Converting kilometers to miles miles = km * fact
Now, we multiply the distance in kilometers by fact. This gives us the distance in miles.
# Display output print("%.2f kilometers is equal to %.2f miles" %(km, miles))
Finally, the converted distance is displayed on the screen using print() function.
Python Program to Convert Kilometers to Miles Using Functions
# Python Program to Convert Kilometers to Miles Using Functions # defining the custom function def km_to_miles(num): result = num * 0.621371 return result # Asking for input km = float(input("Enter the distance in kilometers: ")) # Calling out the function miles = km_to_miles(km) # Display output print("%.2f in kilometers is equal to %.2f" %(km, miles))
Output
Enter the distance in kilometers: 5
5.00 in kilometers is equal to 3.11
Conclusion
I hope after going through this post, you understand how to convert kilometers to miles using Python Programming language.
If you have any problem regarding the program, feel free to contact us in the comment section. We will be delighted to assist you.
Also Read: