(Conversion from miles to kilometers) Write a program that displays the following table (note that 1 mile is 1.609 kilometers):
Miles
Kilometers
1
1.609
2
3.218
…
9
14.481
10
16.090
The Correct Answer and Explanation is :
Here’s the Python program to display the table:
# Conversion factor from miles to kilometers
conversion_factor = 1.609
# Print the header of the table
print(f"{'Miles':<10}{'Kilometers':<10}")
print("-" * 20)
# Generate the table for miles 1 to 10
for miles in range(1, 11):
kilometers = miles * conversion_factor
print(f"{miles:<10}{kilometers:<10.3f}")
Output:
Miles Kilometers
--------------------
1 1.609
2 3.218
3 4.827
4 6.436
5 8.045
6 9.654
7 11.263
8 12.872
9 14.481
10 16.090
Explanation:
- Conversion Factor:
- One mile is equal to 1.609 kilometers. This constant is stored in the variable
conversion_factor.
- Table Header:
- The header row displays “Miles” and “Kilometers” for clarity. The formatting ensures proper alignment using
f-stringswith<10, which reserves 10 spaces for alignment.
- Range of Miles:
- A
forloop iterates over the numbers 1 to 10 (inclusive). Therange(1, 11)function generates these numbers.
- Conversion:
- For each mile in the loop, the equivalent distance in kilometers is calculated by multiplying the miles value by the
conversion_factor.
- Formatting:
- The results are printed with proper alignment. The kilometers are formatted to three decimal places using
.3fin thef-string. This ensures the table looks neat and precise.
- Output:
- The program prints the table directly to the console, starting from 1 mile (1.609 kilometers) to 10 miles (16.090 kilometers).
Why It Works:
- The code is structured to handle the conversion dynamically.
- It uses simple and effective techniques, like a
forloop and formatted strings, making it clear and easy to read. - If you wanted to extend this table (e.g., up to 20 miles), you would only need to update the
range()function.