Advertisement
llsumitll

fuel log

Oct 13th, 2024 (edited)
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.26 KB | Source Code | 0 0
  1. import json
  2. from datetime import datetime
  3. import os
  4.  
  5. class FuelLog:
  6.     def __init__(self, filename='fuel_logs.json'):
  7.         self.filename = filename
  8.         self.logs = self.load_logs()
  9.  
  10.     def load_logs(self):
  11.         """Load logs from the JSON file."""
  12.         if os.path.exists(self.filename):
  13.             with open(self.filename, 'r') as file:
  14.                 return json.load(file)
  15.         return []
  16.  
  17.     def save_logs(self):
  18.         """Save logs to the JSON file."""
  19.         with open(self.filename, 'w') as file:
  20.             json.dump(self.logs, file, indent=4)
  21.  
  22.     def add_log(self, date_time, odometer_reading, liters_filled, total_amount):
  23.         self.logs.append({
  24.             'date_time': date_time,
  25.             'odometer_reading': odometer_reading,
  26.             'liters_filled': liters_filled,
  27.             'total_amount': total_amount
  28.         })
  29.         self.save_logs()  # Save logs after adding
  30.  
  31.     def get_logs(self):
  32.         return self.logs
  33.  
  34.     def calculate_average_consumption(self):
  35.         if not self.logs:
  36.             return 0
  37.         total_liters = sum(log['liters_filled'] for log in self.logs)
  38.         total_distance = sum(log['odometer_reading'] for log in self.logs)
  39.         if total_distance == 0:
  40.             return 0
  41.         return total_liters / total_distance * 100  # L/100 km
  42.  
  43.  
  44. def display_menu():
  45.     print("\nFuel Management Application")
  46.     print("1. Add Fuel Log")
  47.     print("2. View Fuel Logs")
  48.     print("3. Calculate Average Consumption")
  49.     print("4. Exit")
  50.  
  51.  
  52. def main():
  53.     fuel_log = FuelLog()
  54.     while True:
  55.         display_menu()
  56.         choice = input("Choose an option (1-4): ")
  57.  
  58.         if choice == '1':
  59.             date_time = input("Enter Date and Time (YYYY-MM-DD HH:MM): ")
  60.             # Validate the date and time format
  61.             try:
  62.                 datetime.strptime(date_time, '%Y-%m-%d %H:%M')
  63.             except ValueError:
  64.                 print("Invalid date and time format. Please use YYYY-MM-DD HH:MM.")
  65.                 continue
  66.  
  67.             odometer_reading = float(input("Enter Odometer Reading (in km): "))
  68.             liters_filled = float(input("Enter Fuel Filled (in liters): "))
  69.             total_amount = float(input("Enter Total Amount (in currency): "))
  70.             fuel_log.add_log(date_time, odometer_reading, liters_filled, total_amount)
  71.             print("Fuel log added successfully.")
  72.  
  73.         elif choice == '2':
  74.             logs = fuel_log.get_logs()
  75.             if not logs:
  76.                 print("No fuel logs available.")
  77.             else:
  78.                 print("\nFuel Logs:")
  79.                 for i, log in enumerate(logs, start=1):
  80.                     print(f"• {i}. Date & Time: {log['date_time']}, Odometer: {log['odometer_reading']} km, "
  81.                           f"Liters: {log['liters_filled']}, Total Amount: {log['total_amount']}\n")
  82.  
  83.         elif choice == '3':
  84.             average_consumption = fuel_log.calculate_average_consumption()
  85.             print(f"Average Fuel Consumption: {average_consumption:.2f} L/100 km\n")
  86.  
  87.         elif choice == '4':
  88.             print("Exiting the application.")
  89.             break
  90.  
  91.         else:
  92.             print("Invalid option. Please try again.")
  93.  
  94.  
  95. if __name__ == "__main__":
  96.     main()
  97.  
Tags: python fuel
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement