Advertisement
Guest User

Untitled

a guest
Mar 28th, 2020
91
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 3.19 KB | None | 0 0
  1. import csv
  2.  
  3. def readData():
  4.     fields = ("name", "city", "miles", "gallons")
  5.     f = open("travel.txt", "r")
  6.     travels = []    # create empty list
  7.  
  8.     dReader = csv.DictReader(f, fieldnames=fields, delimiter="\t")  # read file f, using fields by tab
  9.  
  10.     for row in dReader: # each row is converted to a dictionary
  11.         travels.append(row) # append dictionary to list
  12.  
  13.     f.close()
  14.     return travels  # return list of dictionaries
  15.  
  16. def displayData(trips):     # trips is the list of dictionaries
  17.     fs = "%-8s %-16s %7s %s"    # create format string
  18.     print(fs % ("Name", "City", "Miles", "Gallons"))    # print header
  19.     print()
  20.     for t in trips:                 # t is a dictionary
  21.         fs = "%-8s %-16s %6s %5s"   # makes format string
  22.         print(fs % (t['name'].title(), t['city'].title(), t['miles'], t['gallons']))
  23.  
  24. def calculateData(trips):
  25.     totalM = []
  26.     totalG = []
  27.     print()
  28.     userName = input("Enter user's first name: ").lower()
  29.     print()
  30.     for row in trips:
  31.         if row.get('name') == userName:
  32.             totalM.append(float(row.get('miles')))
  33.             totalG.append(float(row.get('gallons')))
  34.             totalMiles = sum(totalM)
  35.             totalGallons = sum(totalG)
  36.     mpg = totalMiles / totalGallons
  37.     cost = totalMiles * 0.75
  38.     print('Name: ', userName.title())
  39.     print("Total miles: ", "%.2f" % totalMiles)
  40.     print("Total gallons: ", "%.2f" % totalGallons)
  41.     print("mpg = ", "%.2f" % mpg)
  42.     print("Owed: $", "%.2f" % cost, "at 75 cents per mile")            
  43.            
  44. def addTrip(trips):
  45.     nom = input("Enter your first name: ")
  46.     city = input("Enter destination city: ")
  47.     mi = input("Enter miles traveled: ")    # get user input, create dictionary, add to list
  48.     gal = input( "Enter gallons used: ")    # all the data are strings
  49.     record = {'name' : nom, 'city' : city, 'miles' : mi, 'gallons' : gal}   # create the dictionary
  50.     trips.append(record)                    # append dictionary to list
  51.     return trips
  52.  
  53. def storeData(trips):
  54.     fields = ("name", "city", "miles", "gallons")
  55.     f = open("travel.txt", "w")
  56.     dWriter = csv.DictWriter(f, fieldnames=fields, delimiter="\t", lineterminator="\n") # get file ready
  57.     dWriter.writerows(trips)    # write the whole list of dictionaries to tab separated text file
  58.  
  59.     f.close()
  60.  
  61. def main():
  62.     travel_log = readData()   # read file, convert records to a list of dictionaries
  63.     while True:
  64.         print("""
  65. Menu options. Choose 1, 2, 3, or 4
  66. 1. Display all trip data
  67. 2. Calculate user data
  68. 3. Add a trip
  69. 4. Save and exit
  70. """)
  71.         opt = input("   Enter your choice, 1, 2, 3 or 4: ")
  72.         if opt == "1":
  73.             print()         #prints a blank line
  74.             displayData(travel_log)
  75.         elif opt == "2":
  76.             calculateData(travel_log)
  77.         elif opt == "3":
  78.             travel_log = addTrip(travel_log)
  79.         elif opt == "4":
  80.             storeData(travel_log)
  81.             print("Goodbye")
  82.             print()
  83.             break     #exit loop
  84.         else:
  85.             print("Invalid entry, please re-enter your choice")
  86.             print()
  87.            
  88. main() # Call main(), execute the program
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement