5 of 6
Create and print a 4×4 checkerboard pattern:
B W B W
W B W B
B W B W
W B W B
for r in range(4): for c in range(4): if ___: print("B", end=" ") else: print("W", end=" ") print()
Notice that B appears when (row + col) is even, and W when it's odd:
Use the modulo operator %. A number is even when number % 2 == 0.
if (r + c) % 2 == 0:
Make it any size! Ask the user for the number of rows and columns:
rows = int(input("Rows: ")) cols = int(input("Cols: ")) # Print the checkerboard
for r in range(4): for c in range(4): if (r + c) % 2 == 0: print("B", end=" ") else: print("W", end=" ") print()
How it works:
% 2 == 0 check tells us if a number is evenrows = int(input("Rows: ")) cols = int(input("Cols: ")) for r in range(rows): for c in range(cols): if (r + c) % 2 == 0: print("B", end=" ") else: print("W", end=" ") print()