Convert Kilometers to Miles in Python
Multiply by 0.621371. Put the magic number in a named variable so you can find it later.
BeginnerBasic Python ProgramsExample 9 of 25
convert-kilometers-to-miles.py
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")
Output
Enter distance in kilometers: 5 5.0 km is equal to 3.106855 miles
In this one
- name the 0.621371, don't bury it
- round() if you don't want six decimal places
What's going on
1 km ≈ 0.621371 miles. Multiply. That's it.
The named conversion_factor is the useful part. Hard-coding 0.621371 in the print line is how you get a typo you can't search for.
The miles value will look ugly (3.106855). round(miles, 2) if you want it to look like a road sign.
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.