Python 2.2Code walkthrough9 parts

while Loops

Repeat until a condition changes, and avoid infinite loops.

Loading your progress…Next: 2.3 for Loops and range

In this lesson9 parts

  1. 01A question with no known count
  2. 02The while loop: condition, body and iteration
  3. 03Tracing the loop, one iteration at a time
  4. 04How many times does the body run?
  5. 05The infinite loop, and the rule that prevents it
  6. 06A sentinel: looping until an empty entry
  7. 07Input validation: asking again until the answer is usable
  8. 08The assignment expression: reading and testing in one line
  9. 09Recap and your challenge

Key terms

The words this lesson introduces, each in one line. The module’s glossary collects them all.

assignment expression
name := value: assigns a value and gives that value, inside an expression. while (price := input("Price: ")) != "": reads and tests in one condition. Also called the walrus operator.
infinite loop
A loop whose condition never becomes False, because nothing in the body changes what it reads.
iteration
One run of the loop body.
loop
Code that runs its body again and again: a while statement or a for statement, with its block.
loop body
The indented block that repeats.
sentinel
A value that marks the end of the input, and is not processed, such as an empty entry at a checkout.

Quiz 5 questions

Your first pick on each question is the one that counts, and a right one earns a coin. Getting one wrong here is how the lesson sticks.

Practice

Problems to solve in your own notebook. Each states the problem, not the steps: working out the steps is the exercise. Level A applies the lesson, B combines it with earlier ones, C stretches it.

The self-checking notebook for this lesson is Notebook 2 · Loops.

Common mistakes

What you will see when it goes wrong, why it happens, and the fix.

Where it’s used

Where this lesson’s ideas turn up in real work.