在Python 3上
嗨,我有一批产品(作为字典。其中每个键都是标识号,每个值都是信息字典)。该程序接收一个标识号(想要的产品)和所需的数量。 然后代码应该将产品信息添加到空购物篮中,将库存数量编辑为原始数量减去输入的数量。并将购物篮中的金额编辑为所需的金额。
但是,代码始终使库存输出中的产品数量为零。并且购物篮中的产品数量也输出为零。
通过打印命令我想我已经找到了问题所在。下面的 if 语句中的某处。
但它看起来很简单,我不知道我错在哪里!
提前非常感谢。库存和“漂亮”的打印函数位于代码顶部,可帮助您可视化情况
stock = {
'10005' : {
'name' : 'Conference Pears Loose',
'price' : 2.00,
'unit' : 'kg',
'promotion' : None,
'group' : None,
'amount' : 1.550
},
'10013' : {
'name' : 'Emmental Slices 250G',
'price' : 1.75,
'unit' : 'pieces',
'promotion' : 'get2pay1',
'group' : None,
'amount' : 9
},
'10015' : {
'name' : 'Diced Beef 400G',
'price' : 4.50,
'unit' : 'pieces',
'promotion': 'get4pay3',
'group' : 4,
'amount' : 14
}}
def listitems(dct):
"""
inputs dictionary of stock and prints a lovely table showing all the items with info
"""
print("\n")
print(" {0:^5} | {1:<38} | {2:^7} | {3:^11} ".format("Ident", "Product", "Price", "Amount"))
print("-" *7 + "+" + "-" * 40 + "+" + "-" * 9 + "+" + "-"*12 + "+")
for key in sorted(dct):
print(" {:^5} | {name:<38} | {price:>5.2f} £ | {amount:>} {unit:<14}".format(key, **dct[key]))
return
#main code of function
basket = dict()
quantity = input("Number of items? ")
#amount = 6
ident = input("Indentification number? ")
#ident = "10011"
listitems(stock)
try:
quantity = int(quantity)
except ValueError:
try:
quantity = float(quantity)
except ValueError:
print("You have entered a invalid amount")
try:
ident = str(ident)
except ValueError:
print("you have entered a invalid indent.")
#print("amount is ", quantity)
#print("amount in stock ", stock[ident]["amount"])
if quantity > 0:
if quantity < stock[ident]["amount"]:
basket[ident] = stock[ident] #adding the product tp the basket.
basket[ident]["amount"] = quantity
stock[ident]["amount"] = stock[ident]["amount"] - quantity
listitems(stock)
listitems(basket)
print("amount is ", quantity)
print("amount in stock ", stock[ident]["amount"])
print("amount in basket", basket[ident]["amount"])
最佳答案
basket[ident] = stock[ident]
这就是你的问题,存在可变类型,所以这不会产生两个相同的东西,而是一个具有两个不同名称的东西。
basket[ident]["amount"] = quantity # ok with that
# since basket[ident] and stock[ident] are now the same you just subtract the amount you just set to itself
stock[ident]["amount"] = stock[ident]["amount"] - quantity
要做你想做的事,你必须明确表示你想要一份副本:
basket[ident] = stock[ident].copy()
关于python - 添加到购物篮,并从库存中取出等值产品,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36863848/