Today we moved from conditionals to repetition: the while loop, how it can run forever, and how to use it to check whether a number is prime.
1. While Loop Fundamentals
- A
whileloop runs a block repeatedly until its condition becomes false. - The condition is checked before each pass. If it’s false at the start, the block never runs at all.
- Set
count = -5withindex = 0and Python skips the loop entirely, moving straight to the next line. That’s not a bug, it’s the rule.
index = 0
while index < 5:
print("hello")
index = index + 1
2. Infinite Loops
- Forget to increment the counter and the condition never turns false. The program runs forever.
- Ctrl + C in the terminal sends the exit signal and stops it.
- Every
whileloop needs an answer to one question: what makes this condition eventually false?
3. Debugging the Loop
We stepped through the loop in the Python debugger, watching the index change and the condition get re-evaluated on each pass. When a loop misbehaves, don’t stare at the code. Step through it and watch the variables.
4. Prime Number Checker
A prime number is divisible only by 1 and itself.
n = int(input("Enter a number: "))
is_prime = True
i = 2
while i < n:
if n % i == 0:
is_prime = False
break # stop as soon as a divisor is found
i = i + 1
print(is_prime)
input()returns a string, so wrap it inint()before doing arithmetic.breakexits the loop immediately. Once you’ve found one divisor, the answer is settled and further checks are wasted work.- We traced it in the debugger with 5 (prime) and 51 (not prime, since 3 divides it).
✅ Exercises
- Warm-up: sum all multiples of 3 or 5 below 10. The answer is 23, so you can check yourself.
- Project Euler Problem 1: sum all multiples of 3 or 5 below 1000.
- Edge cases: run the prime checker with 0, 1 and -7. Watch what the loop does when
nis small, then decide what the program should say and fix it.
Stretch (optional): once it works, try checking divisors only up to the square root of n. Same answer, far less work.
Remember: attempting the code matters more than getting it right first go. Write it, run it, break it, fix it.
⏭️ Next up: the continue statement, the companion to break.
