Problem with functions not returning what I want

I am writing code for a blackjack game where the output will print a list of each 0-51 value followed by the corresponding value in the game's blackjack. The code I have is as follows:

#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()

      

When I run the program, it outputs the first number as expected and gives (0,11)

, (1,11)

and so on.

The problem is that the second value is not returned according to the operators if

and elif

in the function cardInfo

, instead giving the same value for each iteration. It should return a value that matches the values ​​specified in the if statements, but it just returns the value specified in the first if statement. Can anyone explain why this is or how to fix it?

+3


source to share


2 answers


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

there will always be True

, so you never reachelif

If you were to write it with or, it would be:

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

      



But it would be better to test membership and use inif cardNumber in {0, 13 , 26, 39}

Using set {0, 13 , 26, 39}

testing for membership O(1)

.

In [6]: i = 10

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

      

+2


source


Your statement is if cardNumber == 0 or 13 or 26 or 39

equivalent if (cardNumber == 0) or (13) or (26) or (39)

to where the pairs are placed around booleans.

In Python, everything except empty lists, strings, dictionaries, 0s, etc. is considered True

. Hence yours is if cardNumber == 0 or 13 or 26 or 39

equivalent to if cardNumber == 0 or True or True or True

or if True

.



Perhaps you meant to write if cardNumber in [0, 13, 26, 39]

(or the equivalent, but a little faster if cardNumber in {0, 13, 26, 39}

). Or longer textif cardNumber == 0 or cardNumber == 13 or cardNumber == 26 or cardNumber = 39

+1


source







All Articles