8.2. 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 2 3 4 5 6 7 8 9 10 11 >>> while 1==1: print ("Looping") print ("Forever") Looping Forever Looping Forever Looping Forever Looping Forever

(We stopped the computer around this point.)

Note

Discuss topics in this section with classmates.