Check your understanding of the previous reading: how many times a while loop runs, and the while loop patterns.
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)
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.
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)
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.
Match each description to the appropriate pattern.