此代码要求用户输入一个8位GTIN来订购产品。输入产品数量后,我将其写入单独的(空)收据文件。一旦他们完成订购产品,程序就会停止,打开订单收据文件后,您可以看到订购的产品。
订购产品后,我希望我的收据显示累计订单总额(product_price)。为了做到这一点,我需要创建一个运行总计,但我不理解其他教程。
receipt_out = open("Order Receipt.txt","w")
go_again = True
while go_again==True:
file = open("GTIN_Description.txt","r")
keep_asking = False
while keep_asking==False:
gtin = input("Enter GTIN: ")
keep_asking = gtin.isdigit()
found = False
keep_asking = True
while keep_asking == True:
for fileline in file:
linecontent=fileline.split('\t')
if gtin == linecontent[0]:
product_name = linecontent[1]
gtinprice = float(linecontent[2])
quantity = int(input("Quantity of item: "))
price = gtinprice * quantity
product_price = "£{0:.2f}".format(price)
print (linecontent[1],"for", product_price)
output_to_receipt = ("{}\t{}\t{}\t{}\t{}\n").format(gtin, product_name, quantity, gtinprice, product_price)
print(output_to_receipt)
receipt_out.write(output_to_receipt)
found = True
(我想在这里创建一个运行总计,其中所有整体product_price从用户的输入中加在一起以显示在收据上)
if found == False:
print ("GTIN not found")
more = input("Input 'Y' to continue or 'N' to quit window and be supplied with a receipt of your orders: ")
if more.lower().strip()== "y":
keep_asking = False
elif more.lower().strip()=="n":
receipt_out.write(output_to_receipt)
receipt_out.close()
print("Thank you for ordering with Computer Warehouse")
非常感谢 〜rn01
答案 0 :(得分:2)
这样的东西?
found = False
keep_asking = True
total_price = 0.0 # <--
while keep_asking == True:
for fileline in file:
linecontent=fileline.split('\t')
if gtin == linecontent[0]:
product_name = linecontent[1]
gtinprice = float(linecontent[2])
quantity = int(input("Quantity of item: "))
price = gtinprice * quantity
total_price += price # <--
product_price = "£{0:.2f}".format(price)
print (linecontent[1],"for", product_price)
output_to_receipt = ("{}\t{}\t{}\t{}\t{}\n").format(gtin, product_name, quantity, gtinprice, product_price)
print(output_to_receipt, "\t(total: {})".format(total_price)) # <--
receipt_out.write(output_to_receipt)
found = True