Learning outcomes
By the end of this lecture, you should be able to:- choose between
whileandforcorrectly - convert loop logic from one form to the other
- explain control and readability tradeoffs
- debug loop boundary and update issues
Core comparison table
| Aspect | while | for |
|---|---|---|
| Best use | Unknown iteration count | Known iteration count / iterable traversal |
| Condition control | Explicit condition each cycle | Implicit through iterable/range |
| Manual update needed | Yes (usually) | No (iterator updates itself) |
| Infinite loop risk | Higher (missing update) | Lower in basic for range patterns |
| Readability for counting | Medium | High |
Same task in both styles
Task: print 1 to 5
while:
for:
Converting while -> for
Original:Converting for -> while
Original:Decision rule (exam-safe)
Usefor when:
- iterating over string/list/tuple/set/dict
- running fixed number of times
while when:
- loop depends on runtime condition (e.g., keep asking until valid input)
- stopping point is event-based, not count-based
Typical exam traps
- writing
range(1, n)whennmust be included - forgetting update in
while - using
whilewhere iterable traversal is clearer withfor
Mini debug exercise
Find and fix:- infinite loop when
ibecomes2(update skipped bycontinue)
Practice
- Write sum of
1..nin bothwhileandforstyles. - Print each character of
"college"usingforand thenwhile. - Convert this while loop to for loop:
