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
Besides the for loop, Python provides another iteration construct called the while loop. The general syntax of the while loop is as follows:
while boolean_expression:
#loop body
This loop allows a block of statements to run as long as a Boolean control expression evaluates to True. It is used when the number of iterations is not known to the programmer at the time the code is written. Since the control expression is evaluated before the loop body is executed, the while loop is called a pre-test loop: if the expression is False from the beginning, the loop body is never executed. For the loop to terminate, the statements inside its body must modify (update) the variable(s) involved in the control expression so that, after a certain number of iterations, the Boolean expression becomes False.
Case scenario: input validation
You want to write a piece of code that ensures the players’ names are different. The user first enters the name of the first player and then the name of the second player. After that, a while loop starts and keeps running as long as the Boolean control expression player_name_1 == player_name_2 is True. If the names match, the program reports an error and asks the user to enter the second player’s name again. The while loop is appropriate because it is not possible to know in advance how many iterations will be needed: the user might fix the mistake immediately, or they might repeat the error several times.
The key point is that, inside the loop body, the variable involved in the condition—namely player_name_2—is updated. At each iteration its value is overwritten with new input. In this way, sooner or later player_name_2 will become different from player_name_1, the Boolean expression will evaluate to False, and the loop will terminate.
player_name_1 = input("Enter the name of the first player: ")
player_name_2 = input("Enter the name of the second player: ")
while player_name_1 == player_name_2:
print("The two players' names must be different")
player_name_2 = input("Enter the name of the second player again: ")
print(f"The match between {player_name_1} and {player_name_2} can begin")