В моем вступлении к классу сценариев идея состоит в том, чтобы создать базовый список покупок, который принимает данные от пользователя в виде (предмет, количество, цена). Вы сохраняете их в словаре, а затем спрашиваете пользователя, хотят ли они добавить дополнительные элементы в список или выйти. Если они добавляют больше в список, сценарий хочет, чтобы вы добавили его в «список», в который вложена запись словаря. Когда пользователь выходит из программы, он должен распечатать что-то такого рода.
2 milk at $2.99 ea for a total of: x
1 eggs at 1.99 ea for a total of: x
Grand total: x
Моя проблема: я могу заставить его распечатать таким образом, однако он будет только выводите одну и ту же строку снова и снова. Я проверил, что он добавляет записи в список grocery_history
. Они есть, но когда я зацикливаюсь на них, чтобы распечатать их, он напечатает только первую запись для каждого элемента в списке.
i.e.
2 milk at $2.99 ea for a total of: x
2 milk at $2.99 ea for a total of: x
grand total: x
Я не очень хорош со списками или словарями. Это одна из тех вещей в кодировании, с которыми я борюсь.
Я попытался увеличить значение индекса в списке, и это выдало ошибку.
#Task: Create the empty data structure
grocery_item = {}
grocery_history = []
#Variable used to check if the while loop condition is met
stop = 'go'
choice = ''
while choice != 'q':
item_name = input('Item name: ')
quantity = int(input('Quantity purhcased: '))
cost = float(input('Price per item: '))
GL={'name':item_name, 'number': int(quantity), 'price':float(cost)}
grocery_item.update(GL)
print(GL)
grocery_history.append(GL)
choice = input("Would you like to enter another item?\nType 'c' for continue or 'q' to quit:\n")
if choice == 'q':
#print(grocery_history)
break
elif choice =='c':
continue
print(grocery_history)
grand_total = 0
#Define a 'for' loop.
total = 0
rows = len(grocery_history)
for i in grocery_history:
#Calculate the total cost for the grocery_item.
item_total = grocery_history[0]['number']*grocery_history[0]['price']
#Output the information for the grocery item to match this example:
print(grocery_history[0]['number'], grocery_history[0]['name'], ' @', '$',grocery_history[0]['price'], ' ea', '$', item_total)
#Add the item_total to the grand_total
grand_total += item_total
item_total = 0
#Print the grand total
print(grand_total)