Search code examples
pythonrange

Why range(n) doesn't include numerical value 0?


def get_chess_square_color(column, row):
    if not (column and row in range(9)):
        return ''
    elif column == row:  
        return 'white'
    else:
        return 'black'

assert get_chess_square_color(0, 8) == ''

After writing this function, I notice this code line assert get_chess_square_color(0, 8) == ''

I really don't understand, normally 0 is a part ofrange(9), so I expected get_chess_square_color(0, 8) to return 'white',

Does in this case, range elements don't correspond to their numerical value but instead represent an indexing ?, like

text = 'Look'
print(text[0])

will OUTPUT 'L', 1st character of text indexed by the number 0


Solution

  • The condition if not (column and row in range(9)): is not checking if column is in range(9). It’s only checking if row is in range(9) and whether column is non-zero.

    What you're trying to write should look like this statement if column not in range(9) or row not in range(9):