Flow of Control
The while loop
Write a while loop that stops.
The while loop runs its body again and again, as long as its condition stays true. It is written as while test_condition: followed by the indented body. The condition is checked before every iteration, including the first. So if the condition is false at the start, the body never runs at all.
Something inside the body must change, so that the condition eventually becomes false. If nothing changes, the loop runs forever: an infinite loop, which is a logical error.
An example, a countdown:
- count = 3
- while count > 0: print(count, end=' '); count -= 1
- print('Go!')
It prints 3 2 1 Go!. (The two statements of the loop's body are joined here by a semicolon; in a longer program, they would go on separate, indented lines.) Each time round, count goes down by 1; when it reaches 0, the condition count > 0 becomes false and the loop ends. The end=' ' in print() keeps the output on one line, separated by spaces, instead of starting a new line each time.
Which loop to choose? Use for when you know how many times to repeat (or have a sequence to go through). Use while when you repeat until something happens, such as finding all the factors of a number by testing one divisor after another (the book's Program 6-11).
Practise this lesson
Questions that get harder as you improve, a Tutor that helps without giving the answer away, and progress you can see. Free for every learner.
No account, no email address. Opens the real product.