This is an archived version of the course and is no longer updated. Please find the latest version of the course on the main webpage.

Repetition - while loops

Now we move on to the third basic building block, which is the repetition block.

We discussed the while loop in the pre-sessional videos.

What does the following code do? Try to guess first before running it.

n = 10
while n > 0:
    print(n)
    n = n - 1
print("Happy new year!!")

Also remember that you can nest another while statement (or any building block) inside a loop.

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

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 code will end up in an infinite loop, as previously seen in the pre-sessional video. If you have not done yet so, try fixing the error so that it behaves how you would expect it to.

Here is another way to end up in an infinite loop

while True:
    print("on and...")