Skip to main content

Learning outcomes

By the end of this lecture, you should be able to:
  • choose between while and for correctly
  • convert loop logic from one form to the other
  • explain control and readability tradeoffs
  • debug loop boundary and update issues

Core comparison table

Aspectwhilefor
Best useUnknown iteration countKnown iteration count / iterable traversal
Condition controlExplicit condition each cycleImplicit through iterable/range
Manual update neededYes (usually)No (iterator updates itself)
Infinite loop riskHigher (missing update)Lower in basic for range patterns
Readability for countingMediumHigh

Same task in both styles

Task: print 1 to 5

while:
i = 1
while i <= 5:
    print(i)
    i += 1
for:
for i in range(1, 6):
    print(i)

Converting while -> for

Original:
i = 2
while i <= 10:
    print(i)
    i += 2
Converted:
for i in range(2, 11, 2):
    print(i)

Converting for -> while

Original:
for i in range(3, 12, 3):
    print(i)
Converted:
i = 3
while i < 12:
    print(i)
    i += 3

Decision rule (exam-safe)

Use for when:
  • iterating over string/list/tuple/set/dict
  • running fixed number of times
Use 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) when n must be included
  • forgetting update in while
  • using while where iterable traversal is clearer with for

Mini debug exercise

Find and fix:
i = 1
while i < 10:
    if i % 2 == 0:
        continue
    print(i)
    i += 1
Issue:
  • infinite loop when i becomes 2 (update skipped by continue)
Fix:
i = 1
while i < 10:
    if i % 2 == 0:
        i += 1
        continue
    print(i)
    i += 1

Practice

  1. Write sum of 1..n in both while and for styles.
  2. Print each character of "college" using for and then while.
  3. Convert this while loop to for loop:
i = 10
while i >= 0:
    print(i)
    i -= 2

Answer snippets

for i in range(10, -1, -2):
    print(i)