The Python while Loop
The while loop is Python’s tool for indefinite iteration. Unlike a for loop, which runs a set number of times, a while loop continues to execute a block of code as long as a specified condition remains True.
You use a while loop when you do not know in advance how many times you need to repeat an action. Think of it as telling your program: “Keep doing this action until something changes!”
Basic Syntax
The structure of a while loop is simple and intuitive:
while condition:
# Code block to execute as long as the condition is True
# This block must be indentedwhile: The keyword that starts the loop.condition: A Boolean expression that is checked at the beginning of each iteration. If it evaluates toTrue, the loop’s body runs. If it isFalse, the loop terminates.:: The colon marking the end of thewhiledeclaration.- Indented Block: The code that gets repeated. Crucially, something inside this block should eventually make the
conditionbecomeFalse, otherwise the loop will never stop!
Example: A Simple Countdown
This is the most basic form of a while loop, where a counter variable is manually updated in each iteration:
Example
Output:
The Infinite Loop Trap
If you forget to include a line that changes the condition (like counter -= 1), the condition will remain True forever, and the loop will run endlessly! This is called an infinite loop.
# WARNING: This will loop forever!
# while True:
# print("Still going...")If you ever get stuck in an infinite loop in your local terminal, you can force it to stop by pressing Ctrl+C in your keyboard.
Common Use Cases for while Loops
while loops excel in situations where the exact number of repetitions is not known beforehand.
Controlling Loops with break and continue
Just like for loops, while loops can be controlled dynamically:
break: Exits the loop immediately, regardless of the loop condition.continue: Skips the remaining code inside the current turn and jumps back to check the loop condition again.
Example: Sentinel Values
A sentinel value is a special input value that signals the end of a loop:
Example
Output:
The while-else Clause
The else block in a while loop executes only if the loop terminates naturally (when the condition becomes False). It is skipped completely if the loop is terminated early by a break statement.
Example: Countdown with Possible Interruption
Let us run two countdowns to compare natural finish vs early interruption:
Example
Output:
Practice Problems
Problem 1: Guess the Number Game
Write a simple guessing game where the player must guess the secret number:
PygroundTry It Out
Simulate a guessing game where the secret number is 7, and the user guesses 3, 8, then 7.
Expected Output:
You guessed 3... Too low! You guessed 8... Too high! You guessed 7... You got it! The secret number was 7.