2016-11-13 18 views
1

非常感謝您的幫助。我想在此格式打印出來的訂單:如何讓程序使用正確的小計打印出收據格式?

85791008  Mango-1   £1  3 £3 
86139113 Strawberries-500g £1.50 2 £3 
Total cost of order:      £6 

這是我的代碼:

import csv 

option='yes' 
user_orders=[] 
final_price=0.00 

while option=='yes': 
    data=open('Product information.csv', 'rt') 
    purchase=csv.reader(data) 
    order=input('Please enter the GTIN-8 code of the product you would like to purchase: ') 
    for row in purchase: 
     for field in row: 
      if order in field: 
       quantity=int(input('How much of that item: ')) 
       final_price=quantity*float(row[2]) + final_price 
       receipt=('{} {} {} {} {}'.format(row[0]+'  ', row[1]+'  ', str(quantity)+'  ', "{:10.2f}".format(float(row[2]))+'  ', "{:10.2f}".format(quantity * float(row[2])))) 
       user_orders.append(receipt) 
       print('You have added '+(receipt)) 
       option=input('Would you like to add another iem to your order, yes or no: ') 
       if option=='no': 
        for user_order in user_orders: 
         print('\n' + user_order) 
        print('\nTotal cost of order:             '+ "{:10.2f}".format(final_price)) 

如何編輯這在頂部的格式打印出來?

+0

將最後一個打印語句移出循環,就像它在我的答案中所示。 –

回答

0

您的代碼的主要問題是您已經在循環中聲明瞭默認值,並且在每次迭代時重置(final_price,user_orders)。除此之外,格式化已經搞亂了,你用int類型來表示價格,這不是一個好主意。當csv文件中的價格具有浮點時出錯。

import csv 

option='yes' 
user_orders=[] 
final_price=0.00 

while option=='yes': 
    data=open('Product information.csv', 'rt') 
    purchase=csv.reader(data) 
    order=input('Please enter the GTIN-8 code of the product you would like to purchase: ') 
    for row in purchase: 
     for field in row: 
      if order in field: 
       quantity=int(input('How much of that item: ')) 
       final_price=quantity*float(row[2]) + final_price 
       receipt=('{} {} {} {} {}'.format(row[0]+'  ', row[1]+'  ', str(quantity)+'  ', "{:10.2f}".format(float(row[2]))+'  ', "{:10.2f}".format(quantity * float(row[2])))) 
       user_orders.append(receipt) 
       print('You have added '+(receipt)) 
       option=input('Would you like to add another iem to your order, yes or no: ') 
       if option=='no': 
        for user_order in user_orders: 
         print('\n' + user_order) 
        print('\nTotal cost of order:             '+ "{:10.2f}".format(final_price)) 
+0

嗨尼古拉,感謝您的幫助,但您的代碼不會打印出最終的小計。 :( – Mario

+0

嗨尼古拉,我真的很感謝你的幫助,如果你讀到最上面的原始問題,它解釋了一個新問題 – Mario

+0

尼古拉,謝謝你sooo !!任何機會,你知道如何對齊收據,所以所有的價格都是一致的。 – Mario