Day 14 · ~14m

While Loops & Control Flow

While loops, break, continue, sentinel values, and input validation patterns.

🧑‍💻

We've been using for loops all week — and last week too. for loops with range(), with enumerate(), with zip(). They're great. But when would I use a while loop instead?

👩‍🏫

Good question. Use a while loop when you don't know in advance how many times you need to iterate. A for loop says "do this for each item." A while loop says "keep doing this until a condition becomes false."

Think about the difference between your spreadsheet work: processing every row in a table is a for loop. Waiting for a cell value to hit a threshold before stopping? That's a while loop.

count = 0
while count < 5:
    print(count)
    count += 1
# Prints: 0, 1, 2, 3, 4

The loop checks count < 5 before each iteration. The moment count reaches 5, the condition is False and the loop stops. If you forget count += 1, the condition never changes and you get an infinite loop — the program runs forever.

🧑‍💻

What are break and continue? I saw them in some examples online and wasn't sure when to use them.

👩‍🏫

break exits the loop immediately — no more iterations, no checking the condition. continue skips the rest of the current iteration and jumps back to the top.

# break — stop the loop when we find what we want
numbers = [4, 7, 2, 9, 1, 8]
for n in numbers:
    if n == 9:
        print("Found 9!")
        break
    print(f"Checking {n}...")
# Prints: Checking 4... Checking 7... Checking 2... Found 9!
# continue — skip even numbers
for n in range(10):
    if n % 2 == 0:
        continue
    print(n)
# Prints: 1, 3, 5, 7, 9

Remember yesterday's zip() and enumerate()? break is especially powerful with those — imagine zipping through two columns of your spreadsheet and stopping the moment you find a mismatch.

🧑‍💻

What's a sentinel value? I saw that term in some code comments.

👩‍🏫

A sentinel is a special value that signals "stop." It's a pattern for processing input until you see a specific marker. In real code, -1, 0, "quit", or None are common sentinels.

# Process scores until we see -1
scores = [88, 72, 95, 63, -1, 50]
total = 0
count = 0

for score in scores:
    if score == -1:
        break
    total += score
    count += 1

average = total / count if count > 0 else 0
print(f"Average of {count} scores: {average}")
# Average of 4 scores: 79.5

The -1 isn't a real score — it's the sentinel that tells our loop to stop. The 50 after it is never processed. This is like having a "END OF DATA" marker at the bottom of a spreadsheet column.

🧑‍💻

How would I use a while loop to validate something — like making sure a number is in the right range?

👩‍🏫

This is one of the most practical while loop patterns. You keep asking until the input is valid:

def get_valid_score():
    score = -1
    while score < 0 or score > 100:
        score = int(input("Enter a score (0-100): "))
    return score

The loop runs as long as score is outside the valid range. Once the user enters something between 0 and 100, the condition becomes False and the loop exits. See how yesterday's boolean logic (score < 0 or score > 100) drives the loop condition? Everything connects.

Here's another common pattern — a counter with early exit:

def find_first_failing(scores):
    """Return the index of the first failing score, or -1 if none."""
    i = 0
    while i < len(scores):
        if scores[i] < 60:
            return i
        i += 1
    return -1

result = find_first_failing([88, 72, 55, 90])
print(result)  # 2 (index of score 55)
🧑‍💻

When should I pick while over for?

👩‍🏫

Here's the rule of thumb:

  • for loop — you know what you're iterating over (a list, a range, a string)
  • while loop — you're waiting for a condition to change (user input, search, countdown)

Most of the time in Python, for is the right choice. But when you need while, nothing else will do. Between for with enumerate()/zip() and while with break/continue, you now have the complete loop toolkit. Let's practice.

Practice your skills

Sign up to write and run code in this lesson.

Already have an account? Sign in