While loop
Working with while loop, continue, break keywords
The While Loop
In the previous lesson we used for to repeat code a known number of times. But what if you don't know in advance how many iterations you need? That's where while comes in.
Syntax
The loop checks the condition before each iteration. As soon as it becomes False, the loop stops.
Basic Example
This does the same thing as for i in range(1, 6), but notice that we manage the counter ourselves — we initialize i before the loop and increment it inside. The for loop handles all of that automatically, which is why you should prefer for when the number of iterations is known.
Counting Down
Accumulating a Sum
A very common pattern — keep adding numbers until some condition is met:
Digits of a Number
while is natural when you need to process a number digit by digit. The loop continues as long as there are digits left:
For n = 12345, the loop runs 5 times, each time removing the rightmost digit via //= 10.
Infinite Loops and break
If the condition never becomes False, the loop runs forever — this is called an infinite loop. Sometimes this is actually intentional, and you exit the loop with break:
while True is a common Python pattern for "keep running until we explicitly stop". break immediately exits the loop regardless of the condition.
Another example — searching for the first number divisible by both 7 and 13:
continue
continue skips the rest of the current iteration and jumps back to the condition check:
When to Use while vs for
Use for when you know the number of iterations upfront — iterating over a range or a sequence.
Use while when the exit condition depends on something that changes during execution — user input, a value converging, a search terminating:
Nested While Loops
Just like for, you can nest while loops inside each other. This is useful for problems involving two counters that need independent conditions:
Output — a small multiplication table:
Preventing Infinite Loops
Always make sure the condition will eventually become False or that you have a break. A forgotten update to the loop variable is the most common mistake: