Programming Code Examples

Python Program to Convert Kilometers to Miles2 min read

Write a program to Convert Kilometers to Miles in Python


The code you provided is a simple Python program that converts kilometers to miles.

The program starts by defining a variable kilometers and assigns it the value of 10, then it uses the input() function to prompt the user to enter a value in kilometers. The user’s input is stored as a string, so it needs to be converted to a float using the float() function. The variable kilometers is then assigned the value input by the user.

Then, the program defines a variable conv_fac which holds the conversion factor between kilometers and miles, which is 0.621371.

Next, the program calculates the equivalent number of miles by multiplying the number of kilometers by the conversion factor and assigns the result to the variable miles.

Finally, the program uses the print() function to output the equivalent number of miles to the console. The % operator is used to format the output and insert the value of kilometers and miles into the string that is passed to the print() function. The %0.3f within the string is a format specifier, it tells Python to format the number as a floating-point number with 3 decimal places.

The output will depend on the input provided by the user, for example if the user inputs 15, the output will be “15.000 kilometers is equal to 9.320 miles”

Add comment