Writing a Python program to convert kilometers to miles is a great exercise for beginners to learn basic programming concepts in Python such as input handling, performing arithmetic operations, and output display.
Table of Contents
Python Program that Converts Kilometers to Miles
Here is a simple Python code that converts Km to Mile
km = int(input("Enter the distance in km: "))
# conversion factor
factor=0.621371
#convert km to miles
miles = km * factor
print(f"{km} km is equals to {miles:.2f} miles")
In the above code
- We ask the user to input the value in KM.
- Since
input()
returns a string then we have to convert the string value to a float - Then by applying the conversion formula to convert km in miles, we get the value in miles.
- In the end, using
print()
we printed the result in Miles.
Extend the Program (Optional)
If you want to make the program more robust, consider handling potential errors, such as:
- User inputs that are not numbers
- Negative numbers
This simple Python program teaches you to handle user inputs, perform calculations, and output results. It’s a practical way to get familiar with Python’s syntax and its core concepts.