在 while 循环中使用 kwargs - 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

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

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

抱歉,如果这很具体,但这给我带来了很多麻烦。

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

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

i变量最终以 kwarg 为单位保存最后一项的名称。 这就是为什么它适用于"药水"而不是"石头"。

正如穆罕默德回答的那样,您需要检查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 ()

最新更新