The ChessAIThon project (2025-1-ES01-KA220-VET-000354329) is co-funded by the European Union. The views and opinions expressed in this publication are those of the author(s) only and do not necessarily reflect those of the European Union or the Spanish Service for the Internationalisation of Education (SEPIE). Neither the European Union nor the National Agency SEPIE can be held responsible for them.
Table of Contents
Let us imagine we need to count how many white pawns are left on the chessboard. To do this, we examine the piece on each square and, whenever it is a white pawn, we increment a counter by one. Since the chessboard has 64 squares, this check must be performed 64 times. Python provides a construct called the for loop, which repeats a block of statements a predetermined number of times; this block is called the loop body.
The for Loop
The general syntax of the for loop is as follows:
for var in range (start, stop, step):
#loop body
var is an integer loop variable whose name is chosen by the programmer and can be used inside the loop body. After the keyword in, the built-in range() function generates the sequence of values assigned to var. Its arguments are, in order: the initial value start, the stopping value stop (not included), and the step step, which determines how much var changes at each iteration.
The following code snippet prints to the console all the pieces located in the first column (index 0) of the board.
print("---FIRST COLUMN OF THE BOARD---")
for r in range(0, 8, 1):
print(board[r][0]
Output:
--- FIRST COLUMN OF THE BOARD ---
r
p
.
.
.
.
P
R
The range() function can also be called with:
· two arguments, start and stop. In this case, step defaults to 1.
Since the chessboard is a matrix (a list of lists), to traverse it completely we need two for loops, one inside the other (nested loops):
· The inner loop iterates over the columns (0–7) of a given row.
Example: Finding all White Pawns (“P”)
# Variable incremented by one each time a white pawn occupies a square
pawn_count = 0
# Outer loop: iterates over the rows (r) from 0 to 7
for r in range(8):
# Inner loop: iterates over the columns (c) from 0 to 7
for c in range(8):
# Store the piece found in square (r, c)
piece = board[r][c]
# Check if the content of the variable "piece" is a white pawn
if piece == "P":
print(f"White pawn found at row {r}, column {c}")
pawn_count = pawn_count + 1
# Print to the console the number of white pawns on the board
print(f"Total white pawns found: {pawn_count}")