Create a Gas Cost Calculator using Python

In this tutorial, I'm going to show you two python scripts - one for metric units and one for Imperial units - for calculating the cost of gas for a road trip or an everyday commute.

Create a Gas Cost Calculator using Python
Photo by sippakorn yamkasikorn / Unsplash

In this tutorial, I'm going to show you two python scripts - one for metric units and one for Imperial units - for calculating the cost of gas for a road trip or an everyday commute.

distance = float(input("Enter the total distance in miles: "))
price_per_gallon = float(input("Enter the price of gas per gallon: "))
miles_per_gallon = float(input("Enter the miles per gallon of your vehicle: "))

gallons_needed = distance / miles_per_gallon
cost_of_gas = gallons_needed * price_per_gallon

print(f"The total cost of gas needed is: ${cost_of_gas:.2f}")

This script takes in three user inputs: the total distance in miles, the price of gas per gallon, and the miles per gallon of the user's vehicle. It then calculates the number of gallons needed for the trip by dividing the total distance by the miles per gallon. Finally, it calculates the cost of gas by multiplying the gallons needed by the price per gallon, and it outputs the result to the user.

But what if you use the metric system and want to work with kilometers and litres instead of miles and gallons? No problem! Here's a modified version of the script that works with kilometers and litres:

distance = float(input("Enter the total distance in kilometers: "))
price_per_litre = float(input("Enter the price of gas per litre: "))
km_per_litre = float(input("Enter the kilometers per litre of your vehicle: "))

litres_needed = distance / km_per_litre
cost_of_gas = litres_needed * price_per_litre

print(f"The total cost of gas needed is: ${cost_of_gas:.2f}")

This variation of the script takes in three user inputs as well: the total distance in kilometers, the price of gas per litre, and the kilometers per litre of the user's vehicle. It then calculates the number of litres needed for the trip by dividing the total distance by the kilometers per litre. Finally, it calculates the cost of gas by multiplying the litres needed by the price per litre, and it outputs the result.