while Loops
A while loop keeps running as long as its condition is True. It's the "keep going until" loop β perfect for countdowns, retries, and anything where you don't know in advance how many times you'll repeat.
while loopThe while Loop
The simplest loop in Python β check a condition, run the body, repeat:
Output: 5 4 3 2 1 Liftoff! (each on its own line).
Here's what happens step by step:
5 > 0? True β run bodyStep 2: Print 5, then count becomes 4
Step 3: Check condition:
4 > 0? True β run bodyβ¦and so on untilβ¦
Step 10: Check condition:
0 > 0? False β skip body, continue after loop
The Loop Variable
The variable count is the loop variable. It must change inside the loop β otherwise the condition never becomes False and you get an infinite loop!
count = count - 1, the condition count > 0 stays True forever and your program hangs. Always make sure something inside the loop moves you toward the exit condition.
The Accumulator Pattern
A common use of while: build up a total by adding to it each iteration:
The shorthand += is very common in loops: total += n means the same as total = total + n. Similarly, count -= 1 means count = count - 1.
Challenges
Challenge 1: Countdown
Write a while loop that counts down from start to 1, printing each number, then prints "Liftoff!".
count = start, then while count > 0:Hint 2: Inside the loop:
print(count) then count -= 1Hint 3: Full solution:
count = start / while count > 0: / print(count) / count -= 1Challenge 2: Sum to Target
Use a while loop to add 1 + 2 + 3 + ... until the total reaches or exceeds the target.
while total < target: β keep looping as long as we haven't hit the targetHint 2: Inside:
total += n then n += 1Hint 3: For target=20: 1+2+3+4+5+6 = 21 β₯ 20, so total=21, n=7
Challenge 3: Digit Summer
Calculate the sum of digits in a number using a while loop with % and //.
Example: 1234 β 1+2+3+4 = 10
temp % 10 gives the last digit. temp // 10 removes it.Hint 2:
while temp > 0: then digit_sum += temp % 10 then temp //= 10Hint 3: Trace it: 1234 β digit 4, temp 123 β digit 3, temp 12 β digit 2, temp 1 β digit 1, temp 0 β stop. Sum = 10.
Challenge 4: Collatz Sequence
The Collatz Conjecture: start with any positive integer. If even, divide by 2. If odd, multiply by 3 and add 1. Repeat until you reach 1.
Example: n=6 β 6, 3, 10, 5, 16, 8, 4, 2, 1 (8 steps)
while n != 1: β keep going until we hit 1Hint 2: Inside: if n is even (
n % 2 == 0), set n = n // 2. If odd, set n = n * 3 + 1. Don't forget steps += 1!Hint 3: Print n after each change:
print(n, end=" β ") (or similar).