while Loops
while loops repeat as long as a condition is True. Use them when you don't know in advance how many iterations you need. Be careful to avoid infinite loops!
15 min•By Priygop Team•Updated 2026
while Loop
while Loop
# Basic while loop
count = 0
while count < 5:
print(f"Count: {count}")
count += 1 # Don't forget this!
# Countdown
print("\nCountdown:")
n = 5
while n > 0:
print(n, end=" ")
n -= 1
print("Blast off!")
# User input validation (simulated)
password = ""
attempts = 0
correct = "python123"
while password != correct and attempts < 3:
password = correct if attempts == 2 else "wrong"
attempts += 1
if password == correct:
print(f"\nAccess granted (attempt {attempts})")
else:
print(f"Wrong password (attempt {attempts})")
# while True with break
import random
secret = random.randint(1, 10)
guess = 0
while True:
guess += 1
if guess == secret:
print(f"Found {secret} in {guess} tries!")
breakTip
Tip
Prefer for loops when iterations are known. Use while only when the count depends on a runtime condition (user input, convergence).
Diagram
Loading diagram…
List for mutable sequences, tuple for immutable data, set for unique items
Common Mistake
Warning
Forgetting to update the loop variable creates an infinite loop. Always ensure the condition will eventually become False.
Practice Task
Note
(1) Build a countdown from 10 to 1. (2) Create a guessing game that loops until correct. (3) Add a max-attempts limit with a counter.