This code defines a Python function named `print_sudoku` that takes...

August 28, 2025 at 07:48 AM

def print_sudoku(puzzle): for i in range(9): if i % 3 == 0 and i != 0: print("- - - - - - - - - - - ") for j in range(9): if j % 3 == 0 and j != 0: print(" | ", end="") print(puzzle[i][j], end=" ") print()

This code defines a Python function named print_sudoku that takes a 9x9 list (2D list) called puzzle and prints it in a properly formatted grid structure, resembling a Sudoku board. Here's a detailed breakdown of what it does:

  1. Outer loop (for i in range(9)):

    • This iterates over the rows of the Sudoku grid. i represents the current row.
  2. Dividing rows into blocks:

    • The line if i % 3 == 0 and i != 0: checks if the current row (i) is divisible by 3 (excluding the very first row i == 0).
    • If true, a horizontal dividing line ("- - - - - - - - - - - ") is printed to visually separate 3x3 blocks.
  3. Inner loop (for j in range(9)):

    • This iterates over the columns of the current row. j represents the current column.
  4. Dividing columns into blocks:

    • The line if j % 3 == 0 and j != 0: checks if the current column (j) is divisible by 3 (excluding the very first column j == 0).
    • If true, a vertical separator (" | ") is printed to visually separate 3x3 blocks within the row.
  5. Printing the Sudoku grid values:

    • print(puzzle[i][j], end=" "): Prints the value at the current cell of the grid (row i, column j), staying on the same line.
  6. Moving to the next line at the end of each row:

    • After the inner loop completes (i.e., all columns in the current row are printed), print() is called to move to the next line.

Example Output

If the input puzzle is:

puzzle = [
    [5, 3, 0, 0, 7, 0, 0, 0, 0],
    [6, 0, 0, 1, 9, 5, 0, 0, 0],
    [0, 9, 8, 0, 0, 0, 0, 6, 0],
    [8, 0, 0, 0, 6, 0, 0, 0, 3],
    [4, 0, 0, 8, 0, 3, 0, 0, 1],
    [7, 0, 0, 0, 2, 0, 0, 0, 6],
    [0, 6, 0, 0, 0, 0, 2, 8, 0],
    [0, 0, 0, 4, 1, 9, 0, 0, 5],
    [0, 0, 0, 0, 8, 0, 0, 7, 9]
]
print_sudoku(puzzle)

The output would look like:

5 3 0  |  0 7 0  |  0 0 0 
6 0 0  |  1 9 5  |  0 0 0 
0 9 8  |  0 0 0  |  0 6 0 
- - - - - - - - - - - 
8 0 0  |  0 6 0  |  0 0 3 
4 0 0  |  8 0 3  |  0 0 1 
7 0 0  |  0 2 0  |  0 0 6 
- - - - - - - - - - - 
0 6 0  |  0 0 0  |  2 8 0 
0 0 0  |  4 1 9  |  0 0 5 
0 0 0  |  0 8 0  |  0 7 9 

This is a visual representation of the Sudoku grid with rows and columns divided into 3x3 blocks.

Generate your own explanations
Download our vscode extension
Read other generated explanations

Built by @thebuilderjr
Sponsored by beam analytics
Read our terms and privacy policy
Forked from openai-quickstart-node