我需要打印语句才能打印输入到列表中的每个项目。因此,如果我以1.49的价格购买1个苹果和以3.99的价格购买1个牛奶。输出应显示
当前显示:
这是我的代码:'''
grocery_item = {}
grocery_history = []
'''
stop = 'c'
while stop == 'c':
item_name = input("Item name:\n")
quantity = input("Quantity purchased:\n")
cost = input("Price per item:\n")
grocery_item['name'] = item_name
grocery_item['number'] = quantity
grocery_item['price'] = float(cost)
grocery_history.append(grocery_item)
stop = input("Would you like to enter another item?\n Type 'c' for continue or 'q' to quit:\n")
grand_total = 0
for items in range(0, len(grocery_history)):
item_total = int(grocery_history[items].get('number')) * float(grocery_history[items].get('price'))
grand_total = grand_total + float(item_total)
print(str(grocery_history[items]['number']) + ' ' + str(grocery_history[items]['name']) + ' @ $' + str(grocery_history[items]['price']) + ' ea $' + str('%.2f' % item_total))
item_total = 0
print(str('Grand total: $%.2f' % grand_total))
在while循环内移动grocery_item = {}
。
然后移动print(str(grocery_history[items]['number']) + ' ' + str(grocery_history[items]['name']) + ' @ $' + str(grocery_history[items]['price']) + ' ea $' + str('%.2f' % item_total))
for循环内的行
完整的代码应该是这样,
grocery_history = []
stop = 'c'
while stop == 'c':
grocery_item = {}
item_name = input("Item name:\n")
quantity = input("Quantity purchased:\n")
cost = input("Price per item:\n")
grocery_item['name'] = item_name
grocery_item['number'] = quantity
grocery_item['price'] = float(cost)
grocery_history.append(grocery_item)
stop = input("Would you like to enter another item?\n Type 'c' for continue or 'q' to quit:\n")
grand_total = 0
for items in range(0, len(grocery_history)):
item_total = int(grocery_history[items].get('number')) * float(grocery_history[items].get('price'))
grand_total = grand_total + float(item_total)
print(str(grocery_history[items]['number']) + ' ' + str(grocery_history[items]['name']) + ' @ $' + str(grocery_history[items]['price']) + ' ea $' + str('%.2f' % item_total))
item_total = 0
print(str('Grand total: $%.2f' % grand_total))