Infinite Loops

Getting a computer to repeat a set of statements is simple. Sometimes it can be tricky to get it to stop. Remember that a while loop will execute as long as the logical expression is true. What happens if the logical expression is always true?

So, here’s a program that loops forever.

while 1 == 1:
    print("Looping")
    print("Forever")

Since 1 will always be equal to 1, the two print statements will just be repeated over and over and over again and the logical expression will never be false. We call that an infinite loop, which means a loop that continues forever or until it is forced to stop.

Note

The expression 1 == 1 tests if 1 is equal to 1. Remember that x = 3 sets the value of x to 3, it doesn’t test if x is equal to 3. To do that use x == 3.

We ran the following code in a form of Python where we could stop the computer easily:

 1>>> while 1==1:
 2        print ("Looping")
 3        print ("Forever")
 4Looping
 5Forever
 6Looping
 7Forever
 8Looping
 9Forever
10Looping
11Forever

(We stopped the computer around this point.)

Before you keep reading...

Making great stuff takes time and $$. If you appreciate the book you are reading now and want to keep quality materials free for other students please consider a donation to Runestone Academy. We ask that you consider a $10 donation, but if you can give more thats great, if $10 is too much for your budget we would be happy with whatever you can afford as a show of support.

You have attempted 1 of 2 activities on this page