麻烦的功能没有返回我想要的东西

时间:2014-10-28 01:26:16

标签: python python-3.x

我正在为游戏二十一点编写代码,输出将打印每个值0-51的列表,然后是游戏二十一点中的相应值。我的代码看起来像这样:

#cards.py
def cardInfo(cardNumber):
    if cardNumber == 0 or 13 or 26 or 39:  #if the card is an ace
        bjValue = 11                       #the value is 11 of whatever suit
    elif 1 <= cardNumber <= 8:              #if card is 2-9
        bjValue = cardNumber + 1            #the value is itself of clubs
    elif 9 <= cardNumber <= 12:             #if card is 10-king
        bjValue = 10                        #value is 10 of clubs
    elif 14 <= cardNumber <= 21:            #the same as above for the rest
        bjValue = cardNumber - 12           #with respect to higher suits
    elif 22 <= cardNumber <= 25:
        bjValue = 10
    elif 27 <= cardNumber <= 34:
        bjValue = cardNumber - 25
    elif 35 <= cardNumber <= 38:
        bjValue = 10
    elif 40 <= cardNumber <= 47:
        bjValue = cardNumber - 38
    elif 48 <= cardNumber <= 51:
        bjValue = 10
    total = (cardNumber, bjValue) 
    return total

def main():
    for cardValue in range(0,52):
        stuff = cardInfo(cardValue)
        print (stuff)

main()

当我运行程序时,它会输出第一个数字,并提供(0,11)(1,11)等等。

问题是第二个值没有根据if函数中的elifcardInfo语句返回,而是为每次迭代提供相同的值。它应该返回一个对应于if语句中指定的值的值,但它只返回第一个if语句中给出的值。任何人都可以解释为什么这是或如何解决它?

2 个答案:

答案 0 :(得分:2)

if cardNumber == 0 or 13 or 26 or 39:始终为True,因此您永远无法联系elif

如果你用或写它,那将是:

if cardNumber == 0 or cardNumber ==  13 or cardNumber == 26 or cardNumber== 39:

但最好是测试membership并在if cardNumber in {0, 13 , 26, 39}

中使用

使用set {0, 13 , 26, 39}成员资格测试是O(1)

In [6]: i = 10

In [7]: if i == 0 or 1 or 2: # if 1 evaluates to True
   ...:     print(True)
   ...:     
True

答案 1 :(得分:1)

您的陈述if cardNumber == 0 or 13 or 26 or 39等同于if (cardNumber == 0) or (13) or (26) or (39),其中parens被置于逻辑值附近。

在Python中,与空列表,字符串,字典,0等不同的所有内容都被视为True。因此,您的if cardNumber == 0 or 13 or 26 or 39相当于if cardNumber == 0 or True or True or Trueif True

也许你想写if cardNumber in [0, 13, 26, 39](或等同但速度稍快if cardNumber in {0, 13, 26, 39})。或者,if cardNumber == 0 or cardNumber == 13 or cardNumber == 26 or cardNumber = 39

的较长文字