简体   繁体   中英

A len(list) gives TypeError: object of type 'NoneType' has no len()

I'm trying to make a deck of cards, than take out 2 x 2 and return the result. I would like to avoid an "out of index" error. But I keep getting at the "typeError: object of type 'NoneType' has no len()" error. As I checked here it mostly comes from a function usage, and the cause is the Command-Query principle, but I don't see that happening here.

*** code***


    def deck_creator():
        suits = ("Hearts", "Diamonds", "Clubs", "Spades")
        values = ("A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K")
        deck = []
    
        for suit in suits:
            for value in values:
                card = value + " of "+ suit
                deck.append(card)
    
        return deck
    
    def card_dealer(deck):
        """
        5. Deal two cards to the Dealer and two cards to the Player
        """
        print(type(deck))   # ==> !!! <class 'list'> !!! 
        print(len(deck))    # ==> !!! 52 !!! 
        dealers_cards = []
        players_cards = []
        shorter_then_two = True
        while shorter_then_two == True:
            if len(dealers_cards) < 2 or len(players_cards) < 2 :
                card_number = random.randint(1, (len(deck) + 1))   # typeError: object of type 'NoneType' has no len()
                card = deck[card_number]
                if len(dealers_cards) < 2:
                    dealers_cards.append(card)
                else:
                    players_cards.append(card)
                deck = deck.remove(card)
            else:
                shorter_then_two = False
        return players_cards, dealers_cards
    
    a = deck_creator()
    # print(a)
    b = card_dealer(a)
    # print(b)

result:

card_number = random.randint(1, (len(deck) + 1))   
TypeError: object of type 'NoneType' has no len()
<class 'list'>
52 

I realy can't figure out where becomes the deck list a Nonetype object. Thank you for any help.

That's because you're assigning value back to deck variable, but list.remove(index) returns None , not changed list.

>>> l = [1, 2, 3]
>>> l.remove(1)  # None!
>>> l
[2, 3]

where you are going wrong is in the first if statement of card_dealer method. When you are removing the card from the list you have to do this:

deck.remove(card)  # removing the element

The way you were doing will reassign the list. The remove() doesn't return any value (returns None).

deck = deck.remove(card) # will make the list empty (None).

While removing from the list just follow the first method I've mentioned.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM