Skip to main content

Foundations of Python Programming: Functions First

Section 6.5 Infinite Loops

Although the textbook has a time limit which prevents an active code window from running indefinitely, you’ll still have to wait a little while if your program has an ininite loop. If you accidentally make one outside of the textbook, you won’t have that same protection.
So how can you recognize when you are in danger of making an infinite loop?
First off, if the variable that you are using to determine if the while loop should continue is never reset inside the while loop, then your code will have an infinite loop. (Unless of course you use break to break out of the loop.)
Additionally, if the while condition is while True: and there is no break, then that is another case of an infinite loop!
while True:
    print("Will this stop?")

print("We have escaped.")
Another case where an infinite loop is likely to occur is when you have reassiged the value of the variable used in the while statement in a way that prevents the loop from completing. This is an example below (if it takes too long, try reloading the page and stepping through this example in codelens):
Notice how in this case, b is initally set to 15 outside of the while loop, and then reassigned the value of 5 inside, on line 4. By the time 7 has been added to b on line 6, we then have to check if b is less than 60. Because it isn’t we again run line 4, and set the value of b to 5 again. There is no way to break out of this loop.

Note 6.5.1.

The ActiveCode exercises don’t provide a way to stop an infinite loop like you would find in an IDE. To stop the code running in this book, refresh the page.

Checkpoint 6.5.2.

Sometimes programs can take a while to run, so how can you determine if your code is just talking a while or if it is stuck inside an infinite loop? Print statements are for people, so take advantage of them! You can add print statements to keep track of how your variables are changing as the program processes the instructions given to them. Below is an example of an infinite loop. Try adding print statments to see where it’s coming from. When you’re done, check out the answer to see what our solution was.
The problem is that whenever we add more money to the account, we also increase the value of "enough". As long as "enough_money" increases by an amount less than the additional amount, the loop will eventually terminate.
account_balance = 0
enough_money = 1000
while account_balance < enough_money:
    print("account_balance: ", account_balance)
    print("enough_money: ", enough_money)
    account_balance += 100
    enough_money += 10

print("Final account_balance: ", account_balance)
You have attempted of activities on this page.