Python while Loop: Repeat While a Condition Is True
What Is a while Loop?
A while loop repeats a block of code as long as its condition is True. When the condition becomes False, the loop stops and Python carries on with the line below it.
count = 1
while count <= 3:
print("Hello, Sunny!", count)
count += 1
print("Done")Hello, Sunny! 1 Hello, Sunny! 2 Hello, Sunny! 3 Done
Think of it like eating a bowl of soup: while there's soup in the bowl, take another spoonful. You don't count the spoonfuls first. You keep going until the bowl is empty, then you stop.
A while is an if that repeats
A while line looks almost exactly like an if line from chapter 8: a condition, a colon, an indented block. The difference is what happens after the block:
if | while | |
|---|---|---|
| checks the condition | once | before every round |
| runs the block | 0 or 1 times | 0, 1 or many times |
| after the block | carries on below | goes back up and checks again |
Each trip through the block is called a round (programmers also say an iteration).
- Start: Start
- Step: count = 1
- Decision: Is count 3 or less?yesSay hello, add 1 to count, then ask againnoLeave the loop
- Input or output: Show: Done
- End: End
Different from a for loop
In chapter 10, a for loop went through the items of a list, a string or a range(). A while loop needs none of these: it only needs a condition. That makes it the right loop when you don't know in advance how many rounds you'll need, like "keep asking until the user types done". You'll compare the two loops in topic 4.
A while loop repeats its block as long as its condition is True.