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 don’t know in advance how many times you need to repeat an action. Think of it as telling your program, “Keep doing this 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’sTrue, the loop’s body runs. If it’sFalse, 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.
Example: A Simple Countdown
This is the most basic form of a while loop, where a counter variable is manually updated in each iteration.
Pyground
Create a countdown from 5 down to 1 using a while loop.
Expected Output:
Starting countdown... 5 4 3 2 1 Liftoff!
Output:
If you forget to include a line that changes the condition (like counter -= 1), the condition will always be True, and the loop will run forever! This is called an infinite loop.
Example of an infinite loop (don’t run this!):
# DANGEROUS: This will never stop
# while True:
# print("Still going...")If you ever get stuck in an infinite loop, you can usually stop it by pressing Ctrl+C in your terminal.
Common Use Cases for while Loops
while loops excel in situations where the number of iterations is not known beforehand.
Validating User Input
A while loop is perfect for repeatedly asking a user for input until they provide a valid response.
Pyground
Ask the user to enter a number between 1 and 10 and keep asking until they do.
Expected Output:
Waiting for valid input... '0' is not between 1 and 10. Please try again. Waiting for valid input... '11' is not between 1 and 10. Please try again. Waiting for valid input... Success! You entered 5.
Output:
Controlling while Loops with break and continue
Just like for loops, while loops can be controlled with break and continue.
break: Exits the loop immediately, regardless of thewhilecondition.continue: Skips the rest of the current iteration and goes back to check thewhilecondition again.
Example: Using break for a Sentinel Value
A “sentinel value” is a special input that signals the end of a process.
Pyground
Create a program that adds numbers provided by a user until they enter 'done'.
Expected Output:
User entered: 10 User entered: 20 User entered: 5 User entered: done The final sum is: 35
Output:
The while-else Clause
Similar to for-else, the else block in a while loop executes only if the loop terminates naturally (i.e., its condition becomes False). It does not execute if the loop is terminated by a break statement.
Example: A Risky Countdown
Let’s create a countdown that might be interrupted.
Pyground
Run a countdown from 3. If it completes, print 'Countdown successful'. If it's interrupted at 2, print 'Interrupted'.
Expected Output:
--- Natural Finish --- 3 2 1 Countdown successful! --- Interrupted Finish --- 3 Interrupted!
Output:
Practice Problems
Problem 1: Guess the Number
Write a simple number guessing game. Keep asking the user to guess a number until they get it right.
Pyground
Simulate a number 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.