Python Utility Functions! Mile gallon and liter per hundredkilometre fast smart unit conversion

Mondo Cars Updated on 2024-02-01

In this python tutorial, we have created two functions for converting between miles per gallon and liters per hundred kilometers. The first functionliters_100km_to_miles_gallonConvert liters per hundred kilometers to gallons per mile, and the second functionmiles_gallon_to_liters_100kmThe reverse conversion is achieved. With these two functions, we can easily convert between these two different units. We then show how these functions can be used for user interaction, where the user can choose to convert liters per hundred kilometers to gallons per mile, or gallons per mile to liters per hundred kilometers. This simple program makes unit conversion easy and intuitive.

You can use the following two functions to convert mile-gallons to kilometer-liters and vice versa:

def liters_100km_to_miles_gallon(liters_per_100km):

Convert liters per hundred kilometers to gallons per mile

miles_per_gallon = (100 / (liters_per_100km / 3.785411784 / 1.609344))

return miles_per_gallon

def miles_gallon_to_liters_100km(miles_per_gallon):

Convert gallons per mile to liters per hundred kilometers

liters_per_100km = (100 / (miles_per_gallon * 1.609344 / 3.785411784))

return liters_per_100km

With these two functions, you can convert between them. For example:

Test the Liters 100km to Miles Gallon function

liters_per_100km = 5.6

miles_per_gallon = liters_100km_to_miles_gallon(liters_per_100km)

print(f"liters per 100 kilometers = gallons per mile")

Test the Miles Gallon to Liters 100km function

miles_per_gallon = 40

liters_per_100km = miles_gallon_to_liters_100km(miles_per_gallon)

print(f"Gallons per mile = liters per hundred kilometers")

You can combine these two functions to make it easy to do unit conversions when needed. For example, you can write a program that converts between miles gallons and kilometers of liters based on the user's choice:

def main():

print("Please select the conversion type:")

print("1.liters per 100 kilometers to gallons per mile")

print("2.gallons per mile to liters per 100 kilometers")

choice = int(input("Input option (1 or 2):"))

if choice == 1:

liters_per_100km = float(input("Enter liters per 100 km:"))

miles_per_gallon = liters_100km_to_miles_gallon(liters_per_100km)

print(f"liters per 100 kilometers = gallons per mile")

elif choice == 2:

miles_per_gallon = float(input("Enter gallons per mile:"))

liters_per_100km = miles_gallon_to_liters_100km(miles_per_gallon)

print(f"Gallons per mile = liters per hundred kilometers")

else:

print("For invalid options, enter 1 or 2")

if __name__ == "__main__":

main()

This program will perform the corresponding conversion according to the user's choice. You can modify or extend the program as needed to accommodate more conversion types or add more user interactions.

Related Pages