Lesson 22/48 ยท ๐ Loops & Repetition
๐ Loops & RepetitionLesson 22/48
Phase 3 ยท Loops & Repetition20 min
While Loops, Loop Until Done
Use while loops when you don't know how many times to repeat
A `for` loop runs a known number of times. A `while` loop runs as long as a condition is true, you use it when you don't know in advance how many iterations you need.
How would you approach this? Think first, then expand.
While loop basicspython
count = 1
while count <= 5:
print(count)
count += 1
# prints: 1, 2, 3, 4, 5๐Code TracerStep 1 / 14
trace.py
1count = 0โ
2while count < 3:
3 print(count)
4 count += 1
5print("done")
Variables
No variables yet
Step 1 / 14
Infinite loop danger! If the condition never becomes False, your program runs forever. Always make sure something inside the loop changes the condition.
count += 1 is what stops the loop above.Breaking out of a looppython
# Find first number divisible by 7
n = 1
while True: # runs forever... unless we break
if n % 7 == 0:
print(f"First multiple of 7: {n}")
break # exit the loop immediately
n += 1
# prints: First multiple of 7: 7When to use which:
for loop โ you know the count, or you're iterating over a listwhile loop โ you're waiting for a condition to change (searching, guessing games, retries)Practice Exercises
0/2 solvedExercise 1 of 2easy
โฑ 00:00Countdown
Write a function
Example for
countdown(n) that prints numbers from n down to 1, then prints "Go!".Example for
countdown(5):`54321Go!`solution.py
1 / 2
Exercise 2 of 2medium
โฑ 00:00Digit Sum
Write a function
Example:
digit_sum(n) that returns the sum of all digits of a positive integer.Example:
digit_sum(1234) โ 10 (1+2+3+4)solution.py
2 / 2
Solve all 2 exercises to unlock completion