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:

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

(We stopped the computer around this point.)

    csp-8-2-1: How many lines are in the body of the while loop in shown above?
  • 1
  • All the statements that are indented 4 spaces to the right of the while are part of the body of the loop.
  • 2
  • There are two statements that are indented 4 spaces to the right of the while statement, so there are two statements in the body of this loop.
  • 3
  • There are three lines here total, but not all of them are in the body of the loop.
Next Section - Counting with a While Loop