Check your understanding of the previous reading: how many times a while loop runs, and the while loop patterns.

Question 1

How many times does the loop body below execute?

command = ""
words = []
while command != "quit":
    command = input("Type a word:")
    words.append(command)
print(words)

Select one answer, then check.

  • Not quite. command starts as "", which is not "quit", so the condition is true the first time and the body runs.
  • Correct. command starts as "", so the body runs at least once; after that, it depends on what the user types, and the loop stops once they type quit.
  • Not quite. If the user types quit the first time, the condition is false after one pass, so the body runs only once.
  • Not quite. Nothing in the loop counts the passes: it keeps going for as long as the user types something other than quit.

Question 2

How many times will the code below print? If the loop executes infinitely, then enter -1 instead.

counter = 500
while counter > 1:
    counter = counter - 2
    print(counter)

Show worked solution

counter goes 500, 498, …, 2, 0, and every pass prints the new value: the even numbers from 498 down to 0. That is 498 / 2 + 1 = 250 prints. After printing 0, counter > 1 is false and the loop ends.

Question 3

How many times will the code below print? If the loop executes infinitely, then enter -1 instead.

counter = 500
while counter > 1:
    counter = counter // 2
    print(counter)

Show worked solution

counter // 2 halves the value and rounds down: 250, 125, 62, 31, 15, 7, 3, 1. That is 8 prints; once counter is 1, counter > 1 is false and the loop ends.

Question 4

Match each description to the appropriate pattern.

#DescriptionPattern
1 An infinite loop used to make a program continue indefinitely.
2 Satisfying some complicated constraint by trying many different numbers over and over again.
3 Iterating over numbers, usually in a non-linear fashion.
4 Repeatedly getting text from the user in order until the input is correct.
5 Repeatedly getting text from the user in order to execute commands based on what they enter.