1. Repeat while…
A while loop repeats its indented block as long as its condition is True:
- check the condition
- if True, run the block, then go back to step 1
- if False, carry on after the loop
Something inside the loop must change, so the condition becomes False one day. If n never gets smaller, the loop runs forever (an infinite loop) and the program hangs. Always ask: what moves my loop towards the end?
n = 3
while n > 0:
print("Chai in", n)
n = n - 1
print("Chai ready! ☕")
Challenge: ISRO countdown
Read a number n. Use a while loop to print n, n-1, … down to 1, one number per line. After the loop the program prints Liftoff! 🚀 (already written). For 5 the numbers are 5, 4, 3, 2, 1.