Python-追加时出现错误
在为学校做一个项目时,我在代码中遇到了一个bug。这意味着存储以前输入的数据,然后在代码末尾打印 例: 如果输入item1 item2和item3,则只显示item3的信息,而不是所有信息Python-追加时出现错误,python,list,dictionary,append,Python,List,Dictionary,Append,在为学校做一个项目时,我在代码中遇到了一个bug。这意味着存储以前输入的数据,然后在代码末尾打印 例: 如果输入item1 item2和item3,则只显示item3的信息,而不是所有信息 groceryHistory = [] stop = 'c' while stop != 'q': item_name = input('Item name:\n') quantity = input('Quantity purchased:\n') cost = input('Price
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))
不要用伪值初始化变量,使用while True并在结束时使用break退出循环。按4缩进,而不是按2空格缩进。我认为,您希望在for循环中打印
:
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}')