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

Chapter 3: While loops

More on infinite loops

face Josiah Wang

Here is another way sure fire way to end up in an infinite loop!

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

So avoid doing while True: if you can (unless you have a strong reason to do so). We will talk about ways this might be used later in our lesson.

Another more subtle way of ending up with an infinite loop is when the condition is unlikely to be fulfilled.

import random

random.seed(70053)

x = 9999
while x > 0:
    x = random.random()
    print(x)

In the code above, while random.random() can theoretically produce exactly 0., the likelihood is pretty low. So this piece of code will likely run for a very very very very long time (or maybe does not stop!)

Definitely be careful and make sure that your condition will terminate to avoid ending up with an infinite loop!