Python Program to Convert Kilometer to Miles

In this article, we've created some programs in Python, to convert Kilometer value entered by user at run-time to its equivalent value in Miles. Here are the list of programs:

Before creating these programs, let's see the formula used for conversion.

Kilometer to Miles Formula

The Kilometer to miles formula is:

M = K * (0.621371)

Here M indicates to the value in miles and K indicates to the value in Kilometer.

Kilometer to Miles without Function

To convert Kilometer to miles in Python, you have to ask from user to enter the value of distance in kilometre, then convert that distance into miles using above formula, as shown in the program given below:

print("Enter Kilometer Value: ")
km = float(input())

miles = km * (0.621371)
print("\nEquivalent Value in Miles = ", miles)

Here is the initial output produced by this Python program:

convert kilometre to mile python

Type value in Kilometer say 10 and press ENTER key to find and print its equivalent value in miles as shown in the snapshot given below:

kilometre to mile python

Modified Version of Previous Program

This program uses end= to skip printing of an automatic newline using print(). The str() method is used to convert any type of value to a string type. Since + operator is used to concatenate same type of values. And {:.2f} with format() is used to print the value of variable provided as argument of format(), upto only two decimal places.

print("Enter Kilometer Value: ", end="")
km = float(input())

miles = km * (0.621371)
print("\n" + str(km) + " Kilometer = " + "{:.2f}".format(miles) + " Miles")

Here is its sample run with same user, that is 10 as of previous program's sample run:

python convert Kilometer to miles

Kilometer to Miles using Function

This program is created using a user-defined function named KiloToMile(). The function takes a value (Kilometer) as its argument and returns its equivalent value in miles.

def KiloToMile(k):
    return k * 0.621371

print("Enter Kilometer Value: ", end="")
km = float(input())

m = KiloToMile(km)
print("\n" + str(km) + " Kilometer = " + "{:.2f}".format(m) + " Miles")

Kilometer to Miles using Class

This program uses class and object, and object-oriented feature of Python to do the same job as of previous program.

class fresherearth:
    def KiloToMile(self, k):
        return k * 0.621371

print("Enter Kilometer Value: ", end="")
km = float(input())

ob = fresherearth()
m = ob.KiloToMile(km)
print("\n" + str(km) + " Kilometer = " + "{:.2f}".format(m) + " Miles")

In above program, an object named ob is created of class fresherearth to access its member function named KiloToMile() using dot (.) operator.

Python Online Test


« Previous Program Next Program »