Python字典没有正确更新

2024-04-26 03:55:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在试着运行这个超级市场程序。 但是,项目列表没有正确更新。你知道吗

stock = {
    "banana": 6,"apple": 0,"orange": 32,"pear": 15
}    
prices = {
    "banana": 4,"apple": 2,"orange": 1.5,"pear": 3
}

def compute_bill(food):
    total = 0
    for item in food:
        if stock[item] > 0:
            total += prices[item]
            stock[item] -= 1
    return total

print "\n"
print "     Welcome to Supermarket!"
print "List of grocery items :"
print("{:<5}{:<8}{:<9}{:<10}".format("Num","Item","  Cost","  In Stock"))
counter = 0
for x,y in enumerate(prices.items()):
    print("{:<5}{:<10}RS {:.2f}{:>5}".format(x+1,y[0],y[1],stock.values()[counter]))
    counter += 1

print "Specify the number of items : "
number = int (raw_input ())
order = {}
for i in range(number):
    groceryitem = raw_input("Please enter the name of product %s:" % (i+1))
    itemNo = int(raw_input("How many iteam %s ?" % groceryitem))
    order[groceryitem] = itemNo

total = compute_bill(order)
print "total",total

counter = 0
for x,y in enumerate(prices.items()):
    print("{:<5}{:<10}RS {:.2f}{:>5}".format(x+1,y[0],y[1],stock.values()[counter]))
    counter += 1

这低于我得到的输入和输出

                Welcome to Supermarket!
List of grocery items :
Num  Item      Cost     In Stock
1    orange    RS 1.50   32
2    pear      RS 3.00   15
3    banana    RS 4.00    6
4    apple     RS 2.00    0
Specify the number of items :
2
Please enter the name of product 1:banana
How many iteam banana ?4
Please enter the name of product 2:pear
How many iteam pear ?5

Num  Item      Cost     In Stock
1    orange    RS 1.50   32
2    pear      RS 3.00   14
3    banana    RS 4.00    5
4    apple     RS 2.00    0

因为,我已经指定了4个香蕉和5个梨,这些都不应该从库存清单中减去。 为什么股票字典中的值没有更新。你知道吗

请帮帮我!你知道吗


Tags: oftheappleforstockcounteritemsitem
1条回答
网友
1楼 · 发布于 2024-04-26 03:55:45

它们正在得到更新,但是它们只减少了一个,因为您编写了stock[item] -= 1。如果你想减少购买物品的数量,你需要把它改成stock[item] -= food[item]。您可能还想做total += food[item]*prices[item],这样“购物者”就可以根据购买的商品数量正确地收费。你知道吗

相关问题 更多 >