Hello Python Discourse community! I’m new here, working through Python basics and excited to join this awesome forum. I’m building a command-line tool to analyze fuel costs for my car trips, and I’d love your feedback to improve it and learn some Python best practices.
My project is a simple script that calculates fuel costs based on trip distance, fuel efficiency, and price per liter, with an option to save results to a CSV file for tracking. I got inspired by a straightforward fuel calculator I found at kalkulatorpaliwa.com.pl, which has a clean interface and quick calculations. I want my tool to be similarly user-friendly but run from the terminal for quick use.
Here’s my current script using argparse
for command-line inputs:
import argparse
import csv
import os
def calculate_fuel_cost(distance, efficiency, price):
if distance <= 0 or efficiency <= 0 or price <= 0:
return None, "Error: Inputs must be positive numbers!"
fuel_needed = distance / efficiency
cost = fuel_needed * price
return cost, None
def save_to_csv(trip_data, filename="fuel_log.csv"):
file_exists = os.path.isfile(filename)
with open(filename, 'a', newline='') as f:
writer = csv.writer(f)
if not file_exists:
writer.writerow(["Distance (km)", "Efficiency (km/l)", "Price ($/l)", "Cost ($)"])
writer.writerow(trip_data)
def main():
parser = argparse.ArgumentParser(description="Calculate fuel cost for a trip")
parser.add_argument("--distance", type=float, required=True, help="Trip distance in km")
parser.add_argument("--efficiency", type=float, required=True, help="Fuel efficiency in km/liter")
parser.add_argument("--price", type=float, required=True, help="Fuel price per liter in $")
parser.add_argument("--save", action="store_true", help="Save results to CSV")
args = parser.parse_args()
cost, error = calculate_fuel_cost(args.distance, args.efficiency, args.price)
if error:
print(error)
return
print(f"Total fuel cost: ${cost:.2f}")
if args.save:
save_to_csv([args.distance, args.efficiency, args.price, round(cost, 2)])
print(f"Saved to fuel_log.csv")
if __name__ == "__main__":
main()
Example usage:
python fuel_cost.py --distance 300 --efficiency 14 --price 1.7 --save
This outputs the cost and saves the data to a CSV if --save
is used. I’m aiming to make it as intuitive as the calculator at kalkulatorpaliwa.com.pl, but I’m hitting some roadblocks as a beginner. Questions for the community:
- Is
argparse
the best choice for a command-line interface, or should I look into something likeclick
? - How can I improve error handling for edge cases (e.g., non-numeric inputs or file write issues)?
- Any suggestions for adding stats, like average cost per km across multiple trips in the CSV?
I’d love to hear your thoughts on improving the code or cool features to add (maybe integrating an API for fuel prices?). Thanks for any advice, and thrilled to be part of this community!