Search code examples
pythonnonetype

How to deal with NoneType error in Python?


I have only picked up coding and Python in the past week so this question may seem obvious.

I am trying to create a card game. I have already created my deck of cards and now I'm trying to make a function to remove a card from the deck and to test that I am printing out the deck of cards.

However, when I remove a random card from the deck and then try to print out the properties of the remaining cards in the deck I receive an error. I created a class called Card with attributes name, value, suit I took out parts of the code which were very long and not exactly relevant. I have a list of all my cards called the_deck I tried to account for the error with

"if the_deck[i] is None:continue:"

but that doesn't seem to work. Here is my code and then the error.

def pick_a_card():
    a = random.choice(the_deck)
    print(a.name + " of " + a.suit)
    the_deck = the_deck.remove(a)
    i = 0
    while i <= 51:
        if the_deck[i] is None:
            continue
        else:
            print(the_deck[i].name + " of " + the_deck[i].suit)
        i+=1
pick_a_card() 

The error I get is

TypeError: 'NoneType' object is not subscriptable

This error comes from removing a card from the deck. The rest of the function has no errors.

How do I fix this? Thanks.


Solution

  • I am not sure what your data looks like but this is an example of how to remove a random from a list that may help.

    the_deck = [*range(1, 53, 1)]
    
    def remove_val(the_deck):
        a = random.choice(the_deck)
        the_deck.remove(a)
        print('Value removed:', a)
        print('New deck:', the_deck)
    

    A point of note in your example is that, that @alaniwi pointed out, is that should not re-assign the_deck = the_deck.remove(a) rather it should read the_deck.remove(a). Also, you are not handling the fact that len(the_deck) reduces by 1 every time you remove a card.