在为学校做一个项目时,我在代码中遇到了一个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 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循环中的
print
:相关问题 更多 >
编程相关推荐