简体   繁体   中英

How do I loop the python program infinite times til I type q to quit and have the total cost of input on the next column?

I could not get the code to loop infinite times to increase my csv file and add all the input to create a total cost in next column after price input.

So far I got this setup:

import sys
import csv
import datetime as dt

with open('Receipt Price Total.csv', 'w+',newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Company", "Date", "Total Price", "Total Cost"])
    companyname=input("Enter the company name or type q to quit.\n")
    if companyname == "q":
        quit()
    while True:
        try:
            recieptnumber=float(input("Enter the Reciept Cost by number\n"))
            if 0.01 <= recieptnumber <= 100000:
                break
            elif recieptnumber == "0":
                quit()
        except(ValueError):
            print ("Please enter a number or type q to quit")

    writer.writerow([companyname, "", recieptnumber])
    
    Totalcost = float(sum(recieptnumber))
    writer.writerow([Totalcost])
    print(Totalcost)

Edit: Here is my new code, now I'm trying to get the total sum onto the 2nd row only. It seems to create a new row instead. How do I do that?

with open('Receipt Price Total.csv', 'w',newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Company", "Date", "Total Price"])
    while True:
        companyname=input("Enter the company name or type q to quit.\n")
        if companyname == "q":
            break
            quit()
    # Make an array to keep track of reciept prices
        tclist = []
        isValid=False
        while not isValid:
            try:
                Date = input("Type Date of Reciept dd/mm/yy: ")
            # strptime throws an exception if the input doesn't match the pattern
                d1 = dt.datetime.strptime(Date, "%d/%m/%y")
                isValid=True
            # "convert datetime object to a 10 character string"
                d2 = str(d1)[:10]
                if d1 == "q":
                    break
                    quit()
            except (ValueError):
                print ("Try again! dd/mm/yy (example: 09/09/91) or type q to quit")                        
        while True:
            try:
                recieptnumber=float(input("Enter the Reciept Cost by number(example: 0.50)\n$"))
                if 0.01 <= recieptnumber <= 100000:
                    break
                elif recieptnumber == 0.0:
                    break
                    quit()
            except(ValueError):
                print ("Please enter a number or type q to quit")    
        
        # This section needs to be indented foward into the while loop
        # Total cost is a sum of a list
        # You need to have TotalCost in this writerow, or it will be on a new line
        writer.writerow([companyname, d2, recieptnumber])
        
with open ('Receipt Price Total.csv', 'r') as readf, \
     open('Receipt Price Total.csv', 'a', newline='') as appendf:
    writer = csv.writer(appendf)
    reader = csv.reader(readf)
    tclist.append(recieptnumber)
    Totalcost = float(sum(tclist))
    CalList =  [Totalcost]
    for row in reader:
        row.append(CalList)
        writer.writerow(row)
        print(f"Total cost = {Totalcost}")

You just had to indent the writing section forward into the while loop :

import sys
import csv
import datetime as dt

# Opening as w+ will remove all the previous data
with open('Receipt Price Total.csv', 'w+', newline="") as file:
    writer = csv.writer(file)
    writer.writerow(["Company", "Date", "Total Price", "Total Cost"])
    companyname = input("Enter the company name or type q to quit.\n")
    if companyname == "q":
        quit()
    # Make an array to keep track of all entries
    all_list = []
    while True:
        try:
            recieptnumber = input(
                "Enter the Reciept Cost by number. Press q to quit\n")
            if recieptnumber == "q":
                # Hitting q will exit the loop and save the data
                break
            # Now convert to a float
            recieptnumber = float(recieptnumber)
            # Having a high threshold for the min price (100000), may overflow the total price sum
            if 0.01 <= recieptnumber <= 100000:
                break
        except(ValueError):
            # You cant convert q to a float, typing 0 will quit
            print("Please enter a number or type q to quit")
            # Use continue to skip the rest of this loop, and try again
            continue
        all_list.append([companyname, "", recieptnumber])

    # Total cost is a sum of the 3nd element of all list (reciept number)
    Totalcost = float(sum([x[2] for x in all_list]))
    # Write the first row, which has the total cost
    all_list[0].append(Totalcost)
    writer.writerow(all_list[0])
    # Write the rest of the rows
    writer.writerows(all_list[1:])
    print(f"\nSaved.\nTotal cost = {Totalcost}")

I changed a few other things and left a note for each change

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM