Specialty Digest

Global English editionLearners’ Study Dashboard — in development
The Knowledge Library for All

Flashcards: open the module flashcards (end-of-module review with workplace questions).

Online Courses / University Track / Python from Zero

Module 3 · Lesson 2 · Core

while loops: repeating until a condition changes

Write a while loop with a counter and an update, repeat until an input is valid and avoid an infinite loop.

  • 50 minutes
  • Serves O3
  • Assumes M3.L1

Phase 1: Prepare

Step 1 Warm-up recall

From M3.L1: how many values does range(1, 5) produce?

Private: nothing you type here is sent or stored.

Step 2 Learning goal

By the end of this lesson you can:

  • write a while loop with an update line (Foundation);
  • repeat an input until it is valid (Core);
  • spot an infinite loop and fix it (Core).

Phase 2: Teach

Step 3 A familiar example

A lift keeps going up while the floor number is below the one you pressed. It checks before every floor, and stops when the check fails.

Step 4 Clear explanation

A while loop checks a condition before every pass. While it is True, the block runs again. It stops as soon as the condition is False.

n = 3
while n > 0:
    print(n)
    n = n - 1
print("Go")
3
2
1
Go
Checkn > 0RunblockUpdaten = n - 1Falseleave loop
A while loop checks its condition before every pass. If nothing inside changes the condition, the loop never ends.

The line n = n - 1 is the update. Without it, n stays 3, the condition stays True and the loop never ends. This is an infinite loop. If it happens, stop the program (in most editors, press Ctrl and C).

A common real use is to keep asking until the answer is valid:

age = int(input("Age: "))
while age < 0:
    age = int(input("Age again: "))
print("Age is", age)

If the first age is valid, the loop body never runs. A while loop may run zero times.

Step 5 Worked example (4 marks)

Trace n = 2 then while n < 5: n = n + 2, then print(n).

  1. n = 2: 2 < 5 is True, n becomes 4. (1 mark)
  2. n = 4: 4 < 5 is True, n becomes 6. (1 mark)
  3. n = 6: 6 < 5 is False, the loop ends. (1 mark)
  4. Answer: 6 is printed. (1 mark)

Go deeper: the professor's notes

A while loop needs an update that can make its condition False in every branch.
Check

Before each pass.

Update

Moves to False.

Exit

Must be reachable.

CheckconditionRunblockUpdatevariableExitFalse
While loop

Check

BranchUpdates?
normal dayyes
day 366no, so stuck

At work: A stuck loop

The condition never becomes False.

  1. Find every path through the block.
  2. Add an update to each.

What a careful practitioner decides. Test the extreme case, such as the last day of a leap year.

Phase 3: Practise

Step 6 Learner practice (instant-marked)

1. A while loop checks its condition:

2. An infinite loop happens when:

3. How many times does while 5 < 3: run its block?

4. With n = 3, while n > 0: print(n); n = n - 1 prints:

Phase 4: Close

Step 7 Recap

  • A while loop repeats while its condition is True.
  • An update line must move the condition towards False.
  • A while loop can run zero times.

Step 8 Exit ticket (ungraded)

Write a while loop that prints 10, 8, 6, 4, 2.

Private: nothing you type here is sent or stored.

Step 9 Go further (Extension)

Write a program that keeps asking for a password until the user types the right one.

In industry: Zune: a loop that never ended

On 31 December 2008 a clock routine in the 30GB Zune kept repeating a loop while the days left were more than 365. On day 366 of the leap year, nothing inside the loop reduced the count, so it never ended.

Link to this lesson. Every while loop needs an update that moves it towards False, in every branch.

Source: Microsoft engineering blog, Hello w0rld0; TechCrunch, 31 Dec 2008

Common mistakes

MistakeWhy it fails
Forgetting the update lineThe loop never ends.
Updating in the wrong directionn = n + 1 will never make n > 0 False.
Expecting the body to run at least onceIt runs zero times if the condition starts False.

Limits. Other ways out of a loop, such as break, are not needed here.

Flashcards for this lesson (3)

Tap a card to reveal the answer. Read the question, answer it aloud or in writing first, then check yourself against the explanation.

Card 1 of 3 · What does a while loop do?
CheckconditionRunblockUpdatevariable
while loop

It checks its condition before every pass and repeats while it is True. It suits tasks where you do not know the count, such as asking until a form entry is valid.

Card 2 of 3 · What is an infinite loop and how do you fix it?
No updatestuckAdd updaten = n - 1Testends
Infinite loop

A loop whose condition never becomes False. Fix it by adding an update line that moves the condition towards False. Stop a stuck program with Ctrl and C.

Card 3 of 3 · Can a while loop run zero times?
CheckFalseSkipblockContinuebelow
Zero passes

Yes. If the condition is False at the start, the block is skipped. This is correct for a valid input that needs no retry.

Review with flashcards

Test yourself on this module with workplace flashcards and detailed answers.

Open the module flashcards