Sunday, November 17, 2024
Google search engine
HomeData Modelling & AIPython Program to convert Kilometers to Miles

Python Program to convert Kilometers to Miles

Python Program to Convert Kilometers to Miles in Python. A kilometer is a unit of length in the metric system equivalent to 1000 meters. Miles is also a unit of length equal to 1760 yards.

Example:

Input: 5.5 
Output: 3.418 

Formula:

1 kilometer equals 0.62137 miles.
Miles = kilometer * 0.62137   
Kilometer = Miles / 0.62137

Prerequisites: Python Data Types, Python Operators

Convert kilometers to Miles Example

In this example, we multiplied the conversion factor by the kilometer to get the distance in miles using Python operators.

Python3




# driver code
kilometers = 5.5
 
# conversion factor
conv = 0.621371
 
# calculate miles
miles = kilometers * conv
print('%0.3f kilometers is equal to %0.3f miles' % (kilometers, miles))
 
# example 2
kilometers = 6.5
 
# calculate miles
miles = kilometers * conv
print('%0.3f kilometers is equal to %0.3f miles' % (kilometers, miles))


Output:

5.500 kilometers is equal to 3.418 miles
6.500 kilometers is equal to 4.039 miles

Time Complexity: O(1)

Space complexity: O(1)

Convert Kilometers to Miles Using Math module

Here we will use math module.

Python3




import math
 
def km_to_miles(kilometers):
    miles = kilometers * 0.621371 
    return miles
 
# Test the function
kilometers = 10
miles = km_to_miles(kilometers)
print(f"{kilometers} kilometers is equal to {miles} miles.")


Output

10 kilometers is equal to 6.21371 miles.

Feeling lost in the world of random DSA topics, wasting time without progress? It’s time for a change! Join our DSA course, where we’ll guide you on an exciting journey to master DSA efficiently and on schedule.
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 neveropen!

RELATED ARTICLES

Most Popular

Recent Comments