Я искал ответ на это задание около 2 дней. Я обнаружил, что проблемы могут быть схожими, но ни одна из них не отвечает действительности. Я уверен, что это что-то простое, но я возвращаюсь в школу после 18-летнего перерыва. Я пытаюсь добавить элемент в словарь из пользовательского ввода, где мы делаем список покупок. Я продолжаю переписывать свои данные, вместо этого добавляя их в словарь. Я могу добавить его в список в порядке. Для справки вот мой код:
grocery_item = {}
grocery_history = []
#Variable used to check if the while loop condition is met
stop = True
choice=0
grand_total=0
item_total=0
while stop == True:
current_item = {}
current_item["name"]=(input('Item name:\n'))
current_item["quantity"]=int(input('Quantity purchased:\n'))
current_item["cost"]=float(input('Price per item:\n'))
grocery_history.append(current_item)
grocery_item.update(current_item)
print('Would you like to enter another item?')
choice=str(input("Type 'c' for continue or 'q' to quit:\n"))
if choice == 'c':
stop = True
else
stop = False
#grand_total=0
#item_total=0
for i in range(len(grocery_item)):
item_total=(grocery_item['quantity']*grocery_item['cost'])
#print("--------")
#print(grocery_item)
#print(grocery_history)
#print("--------")
grand_total+=item_total
#Output the information for the grocery item to match this example:
#2 apple @ $1.49 ea $2.98
print(grocery_item['quantity'],"",grocery_item['name'],"@","$",grocery_item['cost'],"ea","$" (item_total))
print("Grand total: $", grand_total')
#Set the item_total equal to 0
item_total=0
Для опытных программистов, извините за '#', но я пытался проверить, где я ошибаюсь.
Вот что я получаю:
Item name:
Quantity purchased:
Price per item:
Would you like to enter another item?
Type 'c' for continue or 'q' to quit:
Item name:
Quantity purchased:
Price per item:
Would you like to enter another item?
Type 'c' for continue or 'q' to quit:
Item name:
Quantity purchased:
Price per item:
Would you like to enter another item?
Type 'c' for continue or 'q' to quit:
4 onions @ $ 0.79 ea $ 3.16
4 onions @ $ 0.79 ea $ 3.16
4 onions @ $ 0.79 ea $ 3.16
Grand total: $ 9.48
И вот что я должен получить:
Item name:
Quantity purchased:
Price per item:
Would you like to enter another item?
Type 'c' for continue or 'q' to quit:
Item name:
Quantity purchased:
Price per item:
Would you like to enter another item?
Type 'c' for continue or 'q' to quit:
Item name:
Quantity purchased:
Price per item:
Would you like to enter another item?
Type 'c' for continue or 'q' to quit:
1 milk @ $2.99 ea $2.99
2 eggs @ $3.99 ea $7.98
4 onions @ $0.79 ea $3.16
Grand total: $14.13
Я определил, что список grocery_history правильный, но grocery_item словарь просто перезаписывается последней записью.
Кажется, это Python 3.x из некоторого кода, который я смог использовать, который должен быть 3.x.