在 while 循环中使用 kwargs - Python 3

Using kwargs in while loops - Python 3

在下面的代码中,我试图检查值 (b) 是否是 kwargs 中的键,如果是,则执行剩下的操作。

def shop(**kwargs):
    buy = 1
    print ("Welcome to the shop!")
    for i, v in kwargs.items():
        print ("    ", i, ": ", v)
    while buy == 1:
        b = input ("What would you like to buy? ").lower()
        if b == i.lower():
            if v <= Player.gold:
                Player.gold -= v
                Player.inv_plus(i)
                print ("You bought ", i, "for ", v, "gold!")
                print ("Your gold: ", Player.gold)
                print (Player.show_inv())
                print ()
            else:
                print ("You don't have enough gold!")
                print ()
        elif b == "exit":
            buy = 0
        else:
            print ("We don't sell that item!")
            print ()

shop(Stone=5, Potion=10)

然而,当我尝试 运行 代码时,它总是只允许一个选项。我发现这很难解释,所以我举个例子:

Welcome to the shop!
     Stone :  5
     Potion :  10
What would you like to buy? stone
We don't sell that item!

What would you like to buy? potion
You bought  Potion for  10 gold!
Your gold:  0
Inventory: 
     Potion 6
     Stone 2

它不会接受石头,即使它在字典中,但是它会接受药水。其他时候会相反。

起初我以为是因为它处于 while 循环中,但现在我不太确定了,而且我在其他任何地方都找不到可以帮助我解决这个问题的东西。

对不起,如果这很具体,但这给我带来了很多麻烦。

当您遍历所有项目以打印它们时:

for i, v in kwargs.items():
    print ("    ", i, ": ", v)

i 变量最终保存了 kwargs 中最后一项的名称。这就是为什么它适用于 'potion' 但不适用于 'stone'.

正如 Mohammed 回答的那样,您需要检查 kwargs 中的所有项目,而不仅仅是最后一项。

这可能更好地纳入 try..except 子句:

def shop(**kwargs):
    buy = 1
    print ("Welcome to the shop!")
    for i, v in kwargs.items():
        print ("    ", i, ": ", v)
    while True:
        b = input ("What would you like to buy? ").lower()
        if b == 'exit':
            break
        try:
            v = kwargs[b.capitalize()]
        except KeyError:
            print ("We don't sell that item!")
            print ()
            continue
        if v <= Player.gold:
            Player.gold -= v
            Player.inv_plus(i)
            print ("You bought ", b, "for ", v, "gold!")
            print ("Your gold: ", Player.gold)
            print (Player.show_inv())
            print ()
        else:
            print ("You don't have enough gold!")
            print ()