Python Program to Convert Miles to Kilometers
You can convert miles to kilometers in Python by multiplying the miles value by
1.60934, for example: kilometers = miles * 1.60934.Examples
Input0
Output0.0
Input5
Output8.0467
Input12.5
Output20.11675
How to Think About It
To convert miles to kilometers, understand that 1 mile equals 1.60934 kilometers. So, multiply the number of miles by 1.60934 to get the distance in kilometers.
Algorithm
1
Get the distance in miles from the user.2
Multiply the miles value by 1.60934 to convert to kilometers.3
Display the result in kilometers.Code
python
miles = float(input("Enter distance in miles: ")) kilometers = miles * 1.60934 print(f"{miles} miles is equal to {kilometers} kilometers")
Output
Enter distance in miles: 5
5.0 miles is equal to 8.0467 kilometers
Dry Run
Let's trace converting 5 miles to kilometers through the code
1
Input miles
User enters 5, so miles = 5.0
2
Calculate kilometers
kilometers = 5.0 * 1.60934 = 8.0467
3
Print result
Output: '5.0 miles is equal to 8.0467 kilometers'
| miles | kilometers |
|---|---|
| 5.0 | 8.0467 |
Why This Works
Step 1: Input conversion
We convert the input string to a float using float() so we can do math with it.
Step 2: Multiplication by conversion factor
Multiplying miles by 1.60934 converts the distance to kilometers because 1 mile equals 1.60934 kilometers.
Step 3: Output formatting
We use an f-string to neatly print the original miles and the converted kilometers.
Alternative Approaches
Using a function
python
def miles_to_km(miles): return miles * 1.60934 miles = float(input("Enter miles: ")) print(f"{miles} miles = {miles_to_km(miles)} kilometers")
This approach organizes the conversion into a reusable function, improving readability and reuse.
Using a constant variable
python
CONVERSION_FACTOR = 1.60934 miles = float(input("Miles: ")) kilometers = miles * CONVERSION_FACTOR print(f"{miles} miles = {kilometers} km")
Using a constant variable makes it easy to update the conversion factor if needed.
Complexity: O(1) time, O(1) space
Time Complexity
The program performs a fixed number of operations (input, multiplication, output), so it runs in constant time.
Space Complexity
Only a few variables are used, so the space used is constant.
Which Approach is Fastest?
All approaches run in constant time and space; using a function adds clarity but no performance difference.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct calculation | O(1) | O(1) | Simple quick scripts |
| Function-based | O(1) | O(1) | Reusable code and clarity |
| Constant variable | O(1) | O(1) | Easy updates to conversion factor |
Always convert input to float before calculations to handle decimal miles correctly.
Forgetting to convert the input string to a number causes errors or incorrect results.