Here’s an example Python code to convert kilometers to miles:
# Get input from user for distance in kilometers kilometers = float(input("Enter distance in kilometers: ")) # Convert kilometers to miles using the conversion factor conversion_factor = 0.621371 miles = kilometers * conversion_factor # Display the result print(f"{kilometers} kilometers is equal to {miles:.2f} miles")
In this code, we first prompt the user to enter the distance in kilometers using the input()
function and convert it to a floating-point number using the float()
function. We then define a conversion factor of 0.621371, which represents the number of miles in one kilometer. We multiply the distance in kilometers by this conversion factor to obtain the distance in miles. Finally, we use the print()
function to display the result to the user, using f-strings to format the output with two decimal places.
When you run this code, it should prompt you to enter a distance in kilometers. After you enter a number, it should convert it to miles and display the result, similar to the following:
Enter distance in kilometers: 10 10.0 kilometers is equal to 6.21 miles
Note that you can modify the conversion factor or the formatting of the output as needed.