A while loop repeats as long as a condition is true. You don’t need to know how many times it will run — it keeps going until something changes.
Real-life example: You try entering a password until you get it right. That’s a while loop in action.
Learning Objectives
By the end of this page, you will:
Understand how while loops work
Write loops that stop when a condition changes
Use break to exit early
Use continue to skip a step
Avoid common infinite loop mistakes
count = 0
while count < 5:
print(count)
count += 1
Output: 0, 1, 2, 3, 4
password = ""
while password != "admin123":
password = input("Enter password: ")
Keeps asking until the correct password is typed.
x = 0
while True:
print(x)
x += 1
if x == 5:
break
Output: 0, 1, 2, 3, 4
x = 0
while x < 6:
x += 1
if x == 4:
continue
print(x)
Output: 1, 2, 3, 5, 6
Mistake
Why it's wrong
How to fix it
while x < 5: but no x += 1
Loop never ends
Add x += 1 inside the loop
Bad condition
Always true or never true
Check logic carefully
Ask the user to type "go". Keep asking until they do
Count from 1 to 6, skip number 4 using continue
Try removing x += 1. What happens? Why?