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")
1 will always be equal to
1, the two
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.)
- All the statements that are indented 4 spaces to the right of the
whileare part of the body of the loop.
- There are two statements that are indented 4 spaces to the right of the
whilestatement, so there are two statements in the body of this loop.
- There are three lines here total, but not all of them are in the body of the loop.
csp-8-2-1: How many lines are in the body of the
while loop in shown above?
Discuss topics in this section with classmates.