“TypeError: argument of type 'NoneType' is

2019-02-27 13:54发布

问题:

Here is some Python code which I wrote to generate a random poker hand, just for the heck of it/for the challenge, but when I try to run it, I get the error above on the line "if card in hand". What's going on, and why is this happening, especially since that line is not iterating?

import random
def pokerHand():
    hand = ["This is your hand:"]
    x = 0
    while x < 5:
        cardNum = random.randrange(13) + 1
        if cardNum == 1:
            cardNum = "Ace of "
        elif cardNum == 11:
            cardNum = "Jack of "
        elif cardNum == 13:
            cardNum = "King of "
        elif cardNum == 12:
        cardNum = "Queen of "
        else:
            cardNum = str(cardNum) + " of "
        cardSuit = random.randrange(4)
        if cardSuit == 0:
            cardSuit = "Clubs"
        elif cardSuit == 1:
            cardSuit = "Diamonds"
        elif cardSuit == 3:
            cardSuit = "Hearts"
        elif cardSuit == 2:
            cardSuit = "Spades"
        card = cardNum + cardSuit
        if card in hand: #<the line of error
            pass
        else:
            hand = hand.append(card)
            x = x + 1
    for xx in hand:
        print xx

回答1:

hand = hand.append(card)

append does not return anything. Change it to:

hand.append(card)



回答2:

the append() method of a list does not return the list, it modifies it in place. thus, after you add the first card (with hand = hand.append(card)), hand is set to the return value of append(), which is None (the return value of methods without an explicit return). You should change it to just be hand.append(card)



回答3:

list.append does not return the list with the value appended, but rather appends the value to the list in-place and returns None. Do this instead:

else:
hand.append(card) ...