samedi 10 octobre 2020

Issue with checking if array item is None or is not None

I have a function that is checking a 2D array for None objects. Sort of like a board game with empty slots(except they contain None). I created the array with None at each spot. When I test if it contains None, it says nope.

I understand it is better to use is and is not rather than == and != . I've heard that None objects can be treated as False in weird cases.

Here is a code snippet:

def set_inhabitants(self,locXY,obj,force=False):
    x = locXY[0]
    y = locXY[1]

    print('The spot contains',self._data[x][y] )
    print('The item here is None? ', end='')
    print (self._data[x][y] is None)
    #Spot is empty
    if self._data[x][y] is None:
        self._data[x][y] = obj
    #Spot is full  
    elif self._data[x][y] is not None and force == False:
        print(locXY, 'Spot is not None. Doing Nothing') 
    elif self._data[x][y] is not None and force == True:
        self._data[x][y] = obj
    
b = Board(2,2)
b.print_array()

b.set_inhabitants( (1,1),'A', force=False) 

print('')
print( b.print_array())

Output:

## Board Data Begin ##

[None]  [None]  

[None]  [None]  

## Board Data End ##

The spot contains [None]
The item here is None? False
(1, 1) Spot is not None. Doing Nothing

## Board Data Begin ##

[None]  [None]  

[None]  [None]  

Board Data End

Aucun commentaire:

Enregistrer un commentaire