Program to determine color of a chessboard square using Python

Suppose we have a chessboard coordinate, that is a string that represents the coordinates of row and column of the chessboard. Below is a chessboard for your reference.

a b c d e f g h 8 7 6 5 4 3 2 1 f5

We have to check whether given cell is white or not, if white return True, otherwise return False.

So, if the input is like coordinate = "f5", then the output will be True (See the highlighted square in the diagram above).

Algorithm

To solve this, we will follow these steps −

  • If ASCII value of coordinate[0] mod 2 is same as coordinate[1] mod 2, then

    • return False (black square)

  • Otherwise,

    • return True (white square)

How It Works

The algorithm works based on the chessboard pattern. In chess notation, columns are labeled 'a' to 'h' and rows are numbered 1 to 8. A square is white if the sum of its column and row positions has different parity (odd + even or even + odd).

Example

Let us see the following implementation to get better understanding −

def solve(coordinate):
    if (ord(coordinate[0])) % 2 == int(coordinate[1]) % 2:
        return False
    else:
        return True

coordinate = "f5"
print(solve(coordinate))

The output of the above code is −

True

Testing Multiple Coordinates

Let's test the function with different chessboard coordinates ?

def solve(coordinate):
    if (ord(coordinate[0])) % 2 == int(coordinate[1]) % 2:
        return False
    else:
        return True

# Test with multiple coordinates
coordinates = ["a1", "a8", "h1", "h8", "f5", "d4"]

for coord in coordinates:
    color = "White" if solve(coord) else "Black"
    print(f"Square {coord}: {color}")
Square a1: Black
Square a8: White
Square h1: White
Square h8: Black
Square f5: White
Square d4: White

Optimized Version

We can simplify the function by directly returning the boolean expression ?

def is_white_square(coordinate):
    return (ord(coordinate[0])) % 2 != int(coordinate[1]) % 2

# Test the optimized version
coordinate = "f5"
print(f"Is {coordinate} white? {is_white_square(coordinate)}")
Is f5 white? True

Conclusion

The chessboard square color can be determined by checking if the column letter's ASCII value and row number have different parity. This elegant solution uses modular arithmetic to identify white squares efficiently.

Updated on: 2026-03-25T20:52:55+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements