Last updated

Python While Loops

Definition: A loop repeats code. A while loop keeps repeating as long as a condition stays True.

Example 1 — counting up

i = 1
while i <= 5:
    print(i)
    i += 1

Each pass checks i <= 5. When i becomes 6, the condition is False and the loop stops. Prints 1 to 5.

Example 2 — the danger of infinite loops

Something inside the loop must move toward stopping it (here i += 1). Forget that and the loop runs forever and freezes the program.

Example 3 — break and continue

  • break — stop the loop right away
  • continue — skip the rest of this pass, go to the next
i = 0
while i < 10:
    i += 1
    if i == 3:
        continue   # skip printing 3
    if i == 6:
        break      # stop at 6
    print(i)

Example 4 — a real pattern

total = 0
n = 1
while n <= 100:
    total += n
    n += 1
print("Sum 1..100 =", total)

💡 When to use: a while loop is best when you do not know how many repeats you need — "keep going until done".

Try it Yourself
Output

          
Ad · responsive