Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on. You've got this! 🚀
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!
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).
for loops for known counts, while loops until a condition is met
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.