Python 杂货清单 Python 3 Codio 挑战

Python Grocery List Python 3 Codio Challenge

所以我正在寻找一种方法,以包含杂货品名称、价格和数量的单独字典的形式将单独的项目添加到列表中。我几周前才开始编程所以请原谅我可怕的代码和初学者的错误。

grocery_item = dict()
current_item = dict()
grocery_history = []
choice = 0
stop = True
while stop == True:
    current_item['name'] = str(input('Item name: '))
    current_item['quantity'] = int(input('Amount purchased: '))
    current_item['cost'] = float(input('Price per item: '))
    grocery_history.append(current_item)
    choice = str(input('Press c to continue or q to quit'))
    if choice == 'c':
        stop = True
    else:
        stop = False
 print(grocery_history)

当我输入两个项目(即垃圾邮件和鸡蛋)的信息时,我得到以下输出:

[{'name': 'Eggs', 'quantity': 12, 'cost': 1.5}, {'name': 'Eggs', 'quantity': 
12, 'cost': 1.5}]

输出只是重复我输入的最新项目,而不是创建两个不同的项目。我犯了一些基本的语义错误,我不知道如何用用户输入循环中的不同项目填充 "grocery_history" 列表。我尝试使用 pythontutor.com 寻求帮助,但被斥为愚蠢。感谢任何帮助。

尝试这样做:

grocery_item = dict()
grocery_history = []
choice = 0
stop = True
while stop == True:
    current_item = dict()
    current_item['name'] = str(input('Item name: '))
    current_item['quantity'] = int(input('Amount purchased: '))
    current_item['cost'] = float(input('Price per item: '))
    grocery_history.append(current_item)
    choice = str(input('Press c to continue or q to quit'))
    if choice == 'c':
        stop = True
    else:
        stop = False
print(grocery_history)

通过在每个循环中创建一个新字典,您将避免您看到的重复错误。

您应该将 current_item 字典移动到 while 中,例如:

while True:
    current_item = {}
    # accepts user inputs here
    grocery_history.append(current_item)
    choice = str(input('Press c to continue or q to quit'))
    if choice != 'c':
        break

一些其他注意事项:

  • 循环前无需启动choice = 0
  • 使用break尽快停止循环,不用再回去检查条件

你得到这个是因为 Python 中的字典是可变对象:这意味着你实际上可以修改它们的字段而无需创建一个全新的字段。

如果您想更深入地了解可变对象和不可变对象之间的主要区别是什么,请关注此link

这是您的代码,稍作修改后可以正常工作:

grocery_history = []
while True:
    name = input('Item name: ').strip()
    quantity = int(input('Amount purchased: '))
    cost = float(input('Price per item: '))
    current_item = {'name':name, 'quantity':quantity, 'cost':cost} 
    grocery_history.append(current_item)
    choice = str(input('Press c to continue or q to quit: '))
    if choice == 'q':
        break
print(grocery_history)