Python-附加错误

问题描述 投票:0回答:1

[在为一个学校项目工作时,我在代码中遇到了一个错误。它是要存储先前输入的数据,然后将其打印在代码的末尾。

EX:如果输入item1 item2和item3,则仅显示item3的信息,而不是所有信息。

groceryHistory = []


stop = 'c'

while stop != 'q':
  item_name = input('Item name:\n')
  quantity = input('Quantity purchased:\n')
  cost = input('Price per item:\n')
#Above Prompts user to enter the item, quantity, and price of the items they're purchasing
  grocery_item = {'name':item_name, 'number': int(quantity), 'price': float(cost)}
  groceryHistory.append(grocery_item)
#Above stores the item within the grocery history list that is held at beginning of code
  stop = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n")
#If user enters q, the loop will end. C will start the loop over again.

grand_total = 0

#Calculating totals using the history that is stored
for grocery_item in groceryHistory:
  item_total = grocery_item['number'] * grocery_item['price']
  grand_total += item_total


print(str(grocery_item['number']) + ' ' + grocery_item['name'] + " @ $"+str(grocery_item['price']) + ' ea $' + str(item_total))

print('Grand total: $' + str(grand_total))
python list dictionary append
1个回答
0
投票

不要使用虚拟值初始化变量,请使用while-True并在结尾处使用break退出循环。缩进4而不是2空格。而且我认为,您需要在for循环中使用print

grocery_history = []
while True:
    item_name = input('Item name:\n')
    quantity = input('Quantity purchased:\n')
    cost = input('Price per item:\n')
    grocery_item = {
        'name': item_name,
        'number': int(quantity),
        'price': float(cost),
    }
    grocery_history.append(grocery_item)
    stop = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n")
    if stop == 'q':
        break

grand_total = 0
for grocery_item in grocery_history:
    item_total = grocery_item['number'] * grocery_item['price']
    grand_total += item_total
    print(f"{grocery_item['number']} {grocery_item['name']} @ ${grocery_item['price']} ea ${item_total}")

print(f'Grand total: ${grand_total}')
© www.soinside.com 2019 - 2024. All rights reserved.