Before you keep reading...
Runestone Academy can only continue if we get support from individuals like you. As a student you are well aware of the high cost of textbooks. Our mission is to provide great books to you for free, but we ask that you consider a $10 donation, more if you can or less if $10 is a burden.
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.
14.6. 👩💻 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 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.
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.