Skip to content
Lesson 9 of 13

Step 1 of 8 · Reading · ~4 min

Learn

Loops and Iteration

While Loops

A for loop has to know its collection before it starts. A while loop does not: it repeats as long as a condition stays true, so the number of passes can be decided while the program is running. After this lesson you can write a loop that stops on a condition you compute, leave one early with break, and skip a single pass with continue.

The shape of a while loop

python

Output: 6. Three pieces: the keyword while, a condition, then a colon and an indented body.

Python tests the condition before every pass:

n = 40   40 > 1 is True  -> body runs, n becomes 20
n = 20   True            -> body runs, n becomes 10
n = 10   True            -> n becomes 5
n = 5    True            -> n becomes 2
n = 2    True            -> n becomes 1
n = 1    1 > 1 is False  -> loop ends, 6 is printed

Because the check comes first, a while whose condition is already false runs zero times — the body is skipped entirely:

python

Something in the body must change the condition

python

That prints 1 forever. The cure is a line inside the body that moves count toward the exit, such as count += 1. Every time you write a while, ask: which value does the condition read, and where in the body does that value change?

break — leave the loop right now

When the stopping rule is easier to state in the middle of the body than in the header, write while True: and break out of it:

python

Output: 3. The -1 is a sentinel: a value that means "no more real data", not a piece of data itself. break jumps to the first line after the loop, so the 4 sitting behind the sentinel is never looked at. Notice that seen is created before the loop — a value you build up across passes has to exist before the first pass runs, and the final print sits after the loop so it happens once.

while True: is not special syntax. The condition is simply always true, so the only way out is break.

continue — skip the rest of this pass

python

This prints 1, 2, 4, 5 on separate lines: when i reaches 3 or 6, continue jumps straight back to the condition without running the print. In a while, put the update before the continue, or the value never changes and the program hangs.

else on a loop

A while or a for may carry an else block, which runs only when the loop ended without a break:

python

This prints composite, because 91 is 7 x 13. Had the loop run out of candidates on its own, the else would have fired instead.

for or while?

Use for when the collection or the repeat count is known up front. Use while when only the stopping rule is known: keep reading until a sentinel arrives, keep halving until you reach 1, keep retrying until it works.

Common mistakes

  • Printing inside the loop instead of after it. A print in the body fires on every pass, so a checker expecting one final line gets a running commentary of partial answers instead.
  • Reading past the sentinel. If you keep consuming input after the stop value instead of breaking, whatever lines follow the sentinel get folded into your answer and it comes out too big.
  • Making the final print conditional. Guarding it with something like if total: means an input that stops immediately prints nothing, and a legitimate answer of 0 vanishes too.
  • Stopping on the wrong test. if value < 1: also fires on every negative number, so negatives end the loop early instead of being processed.

Your exercise

Add up integers that arrive one per line, stopping at the sentinel 0. The starter already creates the accumulator and prints it at the end, so your work is the loop in between. The likeliest mistake is where that print ends up: the checker wants exactly one line, and the sentinel is not part of the total.

Up nextNested Loops and PatternsLoops and Iteration

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…