2016-02-15 59 views
0

在下面的代码中,我试图检查一个值(b)是否是kwargs中的一个键,如果是,则执行其余部分。在while循环中使用kwargs - Python 3

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循环中,但现在我不太确定,而且我找不到任何可以帮助我在其他地方找到的东西。

对不起,如果这是非常具体的,但这给我很多麻烦。

回答

4

当你遍历所有的项目都打印出来:

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

i变量最终持有kwargs的最后一个项目的名称。这就是为什么它适用于'魔药'而不是'石头'。

正如穆罕默德回答,您需要检查所有kwargs中的项目,而不仅仅是最后一个。

+0

“的'i'变量结束了在kwargs抱着最后项目的名字” - 哪里有什么结束了最后的到来完全是任意的,而不是必须连接到调用中的参数顺序,字母顺序或以任何方式一致的任何内容。 – user2357112

0

这可能是更好地分解成一个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() 
+0

我试过了,但没有奏效。我不明白你为什么要做v = kwargs [b.capitalize()]?这难道不会改变B吗?无论哪种方式,你每次都会得到一个KeyError。 – JoeGeC

+0

这条线将小写字母'b'变成例如“石头”变成“kwargs”字典的可能密钥,即“Stone”。如果键不是这样的,你可能需要一些其他的转换。 – xnx