This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 3: While loops

Infinite loops

face Josiah Wang

What does the following code do? Again, try to guess first before verifying your guess by running it yourself.

minute = 5

while minute > 0:
    print(minute)
    second = 60
    while second > 0:
        if second % 10 == 0:
            print(second) 
        second = second - 1

    if minute == 2:
        print("Almost there!")

print("Time's up!!")

In case you have not yet realised, I have purposely made a mistake in the code above. Did you figure out the error?

The program will end up being stuck in an infinite loop.

Infinite loop

If you have not done yet so, try fixing the error so that it behaves how you would expect it to.

The expected output should be as follows:

5
60
50
40
30
20
10
4
60
50
40
30
20
10
3
60
50
40
30
20
10
2
60
50
40
30
20
10
Almost there!
1
60
50
40
30
20
10
Time's up!!

No peeking at the solutions before fixing it yourself! 👀

You only really need to add a single line!

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
minute = 5

while minute > 0:
    print(minute)
    second = 60
    while second > 0:
        if second % 10 == 0:
            print(second) 
        second = second - 1

    if minute == 2:
        print("Almost there!")

    minute = minute - 1

print("Time's up!!")