Добавление информации в словарь Python из пользовательских переменных ввода - PullRequest
2 голосов
/ 01 февраля 2020

Я искал ответ на это задание около 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.

1 Ответ

0 голосов
/ 02 февраля 2020

Некоторый рабочий код здесь для вас:)

stop = True
grocery_history = []
grocery_item = {}
grand_total = 0
#current_item has gone

while stop == True:

    #setdefault helps you to add new values as a list for the existing keys
    grocery_item.setdefault("name",[]).append(input('Item name:\n')) 
    grocery_item.setdefault("quantity",[]).append(int(input('Quantity purchased:\n')))    
    grocery_item.setdefault("cost",[]).append(float(input('Price per item:\n')))

    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

        #This loop helps to iterate sufficiently for given item names 
        for i in range(len(grocery_item['name'])): 

            item_total=(grocery_item['quantity'][i]*grocery_item['cost'][i])
            grand_total+=item_total
            print(grocery_item['quantity'][i],"",grocery_item['name'][i],"@","$",
                  grocery_item['cost'][i],"ea","$",(item_total))
            # This part creates a history item for each sale for the given item names and append it to the grocery_history
            ith_history = [str(i+1)+'.Sale: '+str(grocery_item['quantity'][i]) + ' ' +grocery_item['name'][i] + ' from ' + 
                           str(grocery_item['cost'][i])+' Total: ' +str(item_total)]
            grocery_history.append(ith_history)

print("Grand total: $", grand_total)
#Set the item_total equal to 0
item_total=0

grocery_item.update(current_item) просто обновляя ключи и значения словаря последними заданными ключами и значениями, у вас есть разные значения но одни и те же ключи каждый раз, поэтому у вас есть grocery_item только с последними вводами.

for i in range(len(grocery_item)) будет повторяться 3 раза все время независимо от ввода, потому что len (grocery_item) = 3 ('name', ' количество »,« стоимость »). Вот почему у вас было 3 строки 4 onions @ $ 0.79 ea $ 3.16, хотя в grocery_list было только 1 элемент.

И вот ваш ожидаемый результат с этим кодом:

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
[['1.Sale: 1 milk from 2.99 Total: 2.99'],
 ['2.Sale: 2 eggs from 3.99 Total: 7.98'], 
 ['3.Sale: 4 onions from 0.79 Total: 3.16']]

I wi sh успехов в школе после 18 лет:)

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...