Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to thousands of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Hint: You can adjust the default video playback speed in your account settings.
Hint: You can set your subtitle preferences in your account settings.
Sorry! Looks like there’s an issue with video playback 🙁 This might be due to a temporary outage or because of a configuration issue with your browser. Please refer to our video player troubleshooting guide for assistance.

Infinite Loops

Once in a while you may run into an infinite loop. Sometimes they are necessary and welcomed, but most of the time they are unwanted. In this video you’ll learn what infinite loops are and how they can occur.

00:00 So, one thing you may have run into while dealing with while loops is this idea of a loop that doesn’t end—we called them infinite loops. And this happens whenever we don’t change the condition.

00:14 So if a condition is always returning True, then it’s always going to execute. Let’s show an example. In the one that we’ve been using, n = 5 and we have our while n > 0: we’re going to execute this code.

00:34 Normally, we’re doing n = n - 1, and then we print n. So just to remind you, let’s run this and see what we get.

00:52 All right, so we get our loop, it ends, everything’s fine. Now, what would happen if I took away that first part that is actually decrementing n?

01:07 So, is n ever going to be not 5 if I’m not decrementing it in my loop? No. n is going to stay 5. So if I run this loop…

01:30 we’ll see what happens. See, it’s just going 5, 5, 5, 5, 5, 5, 5, 5, blah, blah, blah, forever and ever and ever. It’s not stopping. That’s an infinite loop right there.

01:41 So if I want to break out, I just hit Control + C and it is forced to reset. So it’s going to stop, you can use that tip whenever you need to break out of an infinite loop. Now, infinite loops can be useful in some senses.

01:54 If you need something to happen forever and you never want something to stop, then you can write an infinite loop. But normally, whenever we are writing our while loops, we always want to make sure that we, at some point, are changing our variable or making sure that our condition becomes False at one point or another, or else we will run into an infinite loop.

stennow on May 11, 2020

feedback. - I like that you use Thonny and use the exelent debugging tool. - I realy hate that you do not move the mouse cursor away from the screen when you write code.

Become a Member to join the conversation.