Goal

You’ll be able to choose correctly between for and while loops, and understand the specific risk that makes while loops more dangerous to write than for loops if you’re not careful.

Learn

A for loop iterates over a known sequence — a fixed number of times, or once per item in a collection:

for i in range(5):
    print(i)  # prints 0, 1, 2, 3, 4

fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
    print(fruit)

A while loop repeats as long as a condition stays True — used when you don’t know in advance exactly how many times you’ll need to repeat:

count = 0
while count < 5:
    print(count)
    count += 1  # this line is essential

Here’s the genuinely important risk: a while loop’s condition must eventually become False, or the loop runs forever — an infinite loop. This happens specifically when the code inside the loop forgets to actually update whatever variable the condition depends on. In the example above, forgetting count += 1 would mean count stays 0 forever, and count < 5 never becomes False.

For loops don’t carry this specific risk in the same way, since they’re bound to a fixed sequence that naturally runs out — this is exactly why a for loop is generally preferred whenever the number of iterations is actually known in advance, reserving while loops for genuinely open-ended repetition, like “keep asking until the user enters valid input.”

Decision Task

You need to keep asking a user for input until they type “quit”. Before reading on: is this a for loop or a while loop situation, and why specifically?

Show Answer

A while loop — you genuinely don’t know in advance how many times the user will need to be asked before typing “quit”; it depends entirely on their behavior at runtime. This is exactly the open-ended repetition case while loops are meant for, unlike a for loop which needs a known, fixed sequence to iterate over.

Common Mistake

Writing a while loop and forgetting to update the variable the condition depends on inside the loop body, creating an infinite loop that never terminates and can freeze or crash a program. Before writing any while loop, it’s worth deliberately checking: what specifically makes this condition eventually False, and is that update actually happening inside the loop body?

Practice Questions

1. Write a for loop that prints the numbers 1 through 10 (inclusive).

Show Answer

for i in range(1, 11):\n print(i) — range(1, 11) generates 1 through 10, since range’s upper bound is exclusive.

2. What specifically causes an infinite loop in a while loop?

Show Answer

The condition never becomes False, typically because the code forgets to update the variable the condition depends on inside the loop body.

3. Given a list of usernames of unknown length, is a for loop or while loop generally the more natural choice for processing each one? Why?

Show Answer

A for loop — the list has a known, fixed sequence of items to iterate over, exactly what for loops are designed for, even though the exact length varies between different lists.

4. True or False: for loops can never accidentally run forever the way while loops can.

Show Answer

True, in the standard sense — a for loop iterating over a fixed sequence naturally terminates once the sequence is exhausted, unlike a while loop whose termination depends entirely on a condition that must be correctly maintained.

5. Write a while loop that keeps a running total, adding 1 each iteration, stopping once the total reaches 5.

Show Answer

total = 0\nwhile total < 5:\n total += 1

Try It Yourself

Without looking back, write a while loop simulating a simple countdown from 5 to 1, printing each number, making sure the loop actually terminates correctly (no infinite loop).

Show Answer

count = 5\nwhile count > 0:\n print(count)\n count -= 1 — count decreases each iteration, eventually making count > 0 False, correctly terminating the loop.

Quick Check

1. When is a for loop generally the right choice?

Show Answer

When iterating over a known, fixed sequence or a known number of repetitions.

2. When is a while loop generally the right choice?

Show Answer

When repetition depends on a condition that isn’t known in advance, like waiting for specific user input.

3. What causes an infinite loop?

Show Answer

A while loop’s condition never becoming False, typically from forgetting to update the relevant variable inside the loop.

4. What does range(5) generate?

Show Answer

0, 1, 2, 3, 4 — five values starting at 0, up to but not including 5.

5. Why should you deliberately check “what makes this condition eventually False” before writing a while loop?

Show Answer

To proactively avoid creating an infinite loop, by confirming the loop body actually updates whatever the condition depends on.

تحميل هذا الباب / Download this Chapterنسخة كاملة للدراسة بدون إنترنت، مع الأسئلة والإجابات والصور المتاحة.