非常感谢你的帮助。我想以这种格式打印出订单:
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))