Chapter 3: While loops

Practice questions

face Josiah Wang

Here are a few questions for you to try to test your understanding of while loops.

1 2 3 4 5 6

Question 1

What is output of the following code snippet? Write multiple outputs on separate lines. Write Infinite if you think the code with run forever without stopping.

timer = 1
while timer <= 5:
    print(timer)
Infinite
Explanation:

I started with a trick question! 😈 Since timer is always 1, the program gets stuck in an infinite loop that never ends! Try this yourself (press CTRL+C to stop the program).

Question 2

What is output of the following code snippet? Write multiple outputs on separate lines. Write Infinite if you think the code with run forever without stopping.

timer = 1
while timer <= 5:
    print(timer)
    timer = timer + 1
1 2 3 4 5
Explanation:

This is the proper version. The program will print 1 to 5 and exit the loop. Always remember to update any counters you have inside your loop!

Question 3

What is output of the following code snippet? Write multiple outputs on separate lines. Write Infinite if you think the code with run forever without stopping.

timer = 1
while timer <= 5:
    print(timer)
    timer = timer - 1
Infinite
Explanation:

Here is another case of an infinite loop. This time, because you are always decreasing timer starting from 1, you will never get out of the loop since timer will always be <= 5. Forever. So be careful of such mistakes!

Question 4

What is output of the following code snippet? Write multiple outputs on separate lines. Write Infinite if you think the code with run forever without stopping.

timer = 0
while timer < 6:
    print(timer)
    timer = timer + 2
0 2 4
Explanation:

Starting with timer == 0, you will increment timer by 2 every time you are in the loop. After the final iteration, timer is 6, which no longer fulfils the while condition timer < 6, so the program exits the loop.

Question 5

What is output of the following code snippet? Write multiple outputs on separate lines. Write Infinite if you think the code with run forever without stopping.

timer = 0
while timer < 6:
    print(timer)
    timer = timer + 2
print(timer)
0 2 4 6
Explanation:

This is the same as the previous verison, except that the program also prints out the value of timer after exiting the loop. This will be 6, since that is the value of timer after exiting the loop.

Question 6

What is output of the following code snippet? Write multiple outputs on separate lines. Write Infinite if you think the code with run forever without stopping.

timer = 0
while timer < 6:
    timer = timer + 2
    print(timer)
print(timer)
2 4 6 6
Explanation:

This time, the program only prints out the value of timer AFTER incrementing its value by 2. So it will print out 6 before exiting the loop, and then print it again outside the loop.