9.1.7 Checkerboard V2 Codehs Info

Use one loop to iterate through each row (0-7) and a nested loop to iterate through each column (0-7).

Create an empty list and use a loop to append 8 sub-lists, each containing eight zeros. 9.1.7 Checkerboard V2 Codehs

Python relies on proper indentation to know which code belongs inside a loop or function. Use one loop to iterate through each row

def print_board(board): for i in range(len(board)): # Joins the list elements into a single string for printing print(" ".join([str(x) for x in board[i]])) # 1. Initialize an 8x8 grid filled with 0s my_grid = [] for i in range(8): my_grid.append([0] * 8) # 2. Use nested loops to assign 1s in a checkerboard pattern for row in range(8): for col in range(8): # 3. Check if the sum of indices is odd or even if (row + col) % 2 != 0: my_grid[row][col] = 1 # 4. Print the final result print_board(my_grid) Use code with caution. Common Pitfalls def print_board(board): for i in range(len(board)): # Joins

To create a checkerboard, we use the row and column indices. If the sum of the and column index is even, we assign one value (e.g., 0); if it is odd, we assign the other (e.g., 1). This is easily checked using the modulo operator ( % ): if (row + col) % 2 == 0: (Sum is even) else: (Sum is odd) Step-by-Step Implementation

Inside the nested loop, use the (row + col) % 2 logic to assign 1 to the correct positions using the syntax grid[row][col] = 1 .

Get Started Now With Shutterstock
This website uses cookies to ensure you get the best experience on our website. Cookie Policy