Python While Loops
A while loop is a loop that repeats a block while a condition stays true. The loop checks the condition before each round.
Count up with while
The condition count <= 3 stays true for three rounds.
count = 1
while count <= 3:
print(count)
count += 1Count down with while
Here count gets smaller each round.
count = 3
while count > 0:
print(count)
count -= 1A condition that starts false
The block is skipped when the condition is false at once.
count = 10
while count < 5:
print(count)
print("Loop never ran")Example
count = 5
while count >= 1:
print(count)
count -= 1
print("Go!")Key points
- Loop: a block of code that runs again and again.
- Use while to repeat a block while a condition is true.
- Iteration: one full run through the loop block.
- The loop checks the condition before each iteration.
- Change the loop variable inside the loop, or the loop never ends.
- Infinite loop: a loop whose condition never becomes false.
In this example, count starts at 5. The loop checks if count is at least 1. It prints count. It then lowers count by 1. The loop repeats until count reaches 0. The condition is then false. The program prints "Go!" after the loop.
Note
Python uses indentation for the loop block.
There are no curly braces around it.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
What must happen inside a while loop so the loop can end?