Python Tutorial · Control Flow · Lesson 21 of 42

Python While Loops

Repeat code while a condition is true, with break, continue and else.

while

A while loop runs as long as its condition is true:

Example 1Try it yourself
count = 1
while count <= 5:
    print(count)
    count += 1

Output

1
2
3
4
5

Make sure something inside the loop changes the condition — otherwise it loops forever.

break and continue

break exits the loop immediately; continue skips to the next iteration.

Example 2Try it yourself
n = 0
while True:
    n += 1
    if n % 2 == 0:
        continue   # skip even numbers
    if n > 7:
        break      # stop the loop
    print(n)

Output

1
3
5
7

while ... else

The else block runs if the loop finished without break — handy for search loops:

Example 3Try it yourself
numbers = [3, 7, 11, 15]
i = 0
while i < len(numbers):
    if numbers[i] % 2 == 0:
        print("Found an even number")
        break
    i += 1
else:
    print("No even numbers")

Output

No even numbers

Test yourself

Which statement exits a loop immediately?

  1. exit
  2. stop
  3. break
  4. continue
Show answer

Answer: break