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.

Breaking Out of an Infinite While Loop

In the previous lesson you learned about infinite loops. This lesson reveals you how you can exit an infinite loop by adding proper logic to your while-loop.

00:00 Okay, so let’s look at our infinite loop example. while True: I’m going to print

00:13 'Hello'. Now, because we are not ever changing this to anything other than True, this should run forever. So, let’s see. Yep, here we go. So it just keeps printing Hello forever and ever and ever because we never told it not to. So if you ever do run into this issue, you can always just hit Control + C and it should interrupt your code from being executed. So that’s just one way to get out of that.

00:45 Okay, so let’s look at how we could use this loop, an infinite loop, but add something, a condition that will let us break out of it. So if I made a variable a and I set it equal to 0 I’m not going to change my condition—it’s going to stay while True—and I’ll keep my print('Hello'), but I am going to add an if statement.

01:09 So let’s say if a == 5: we’re going to break out of my loop, break. Otherwise, I’m going to print 'Hello' and I just want to keep taking a and adding on 1.

01:26 So, take a look at this. Think about how many times you think it’s going to run. Is it going to be an infinite loop still? Did I miss anything? All right, let’s see what happens. There!

01:40 a is equal to 5 and I got Hello printed out five times. So, this never changed and my condition remained True the entire time, so this just kept executing.

01:51 The only thing that made it stop was because it ran into this if statement. So, we can look at this in our debugger

02:02 and see how that happened.

02:07 So we say while True, a didn’t equal 5, so it just went ahead and printed 'Hello'. And then it took that a and it added 1.

02:15 And it’s going to continue to do that

02:21 all the way until a actually equals 5. So, at this point, that if statement, that if condition returns True, so it’s going to execute its code and its code tells it to break.

02:40 So that’s why it breaks out of that loop. All right, so the next thing we’re going to be looking at is nested loops and one-line loops. I’ll see you in the next video.

Become a Member to join the conversation.