Convert Kilometers to Miles in Python
Turn a kilometer measurement into miles with Python float input and a named factor. A first conversion exercise explains units, multiplication, and rounding.
1# Program to convert kilometers to miles23kilometers = float(input("Enter distance in kilometers: "))45conversion_factor = 0.621371 # 1 kilometer = 0.621371 miles6miles = kilometers * conversion_factor78print(kilometers, "km is equal to", miles, "miles")
Sample Output
5.0 km is equal to 3.106855 miles
The sample represents roughly 3.106855 miles; extra trailing float digits may appear.
In this one
- Keep units visible in variable names
- Apply a conversion factor
- Separate calculation from display rounding
How it works
- 1
Convert the entered distance with float.
- 2
Multiply kilometers by conversion_factor and store miles.
- 3
Print both the original distance and the converted value.
Edge cases
Zero distance
Enter 0.
Multiplying by the factor gives 0.0 miles.
Negative distance
Enter -5.
This code produces a negative result because it does not validate physical distance.
What's going on
One kilometer is approximately 0.621371 miles. Multiply the distance by that factor. The units cancel as kilometers times miles per kilometer, leaving miles.
The named conversion_factor is the useful habit here. Burying 0.621371 inside a long print expression makes a typo harder to find. kilometers keeps the original value, while miles stores the converted result.
For 5 kilometers the multiplication gives about 3.106855 miles. The code prints the float directly, so the exact visible digits can reflect binary floating-point representation. round(miles, 2) can shorten a display, but it does not improve the precision of the conversion factor. A negative distance is accepted mathematically; reject it separately if your application requires a non-negative journey length.
After this program
If the idea is still fuzzy, read Day 1: Introduction to Python in the Python course. For a short check, try the Python quiz (300 questions). Stay with all 25 basic python programs, or see every topic on Python exercises.
Quiz
Tap an option. The answer stays hidden until you pick.
Question 1
Why multiply by 0.621371?
Pick an answer to check it.
Question 2
Does round change the conversion formula?
Pick an answer to check it.
Questions people ask
Why multiply by 0.621371?
The factor expresses how many miles correspond to one kilometer.
Does round change the conversion formula?
No. Rounding changes the reported result, not the factor used to compute it.
How would the reverse conversion work?
Divide a miles value by the same kilometers-to-miles factor.