6.12 Control loops with break and next - Video Tutorials & Practice Problems
Video duration:
2m
Play a video:
Video transcript
<v Voiceover>When working with loops,</v> there may be some times when you need to skip an iteration or you need to break out of the loop altogether. Doing that is easy with the next and break statements. So first, let's look at next. We'll build a simple for loop, which says i in one through 10. Remember, i is going to take on the values of one through ten, one at a time, and here we'll say if i is equal to three... next, that means skip this iteration. Then print i. So what this does is if I guessed a three, it's just gonna skip it and this print i will never happen because the next statement automatically goes onto the next iteration of the loop. So if we run this... we see we have one, two, skip the three, four, five, six, seven, seven, eight, nine, 10. Now next can be used to great effect if for some reason, you do some sort of check or something happens inside an iteration, you can skip ahead to the next one. Nice and easy to do. Let's say we need to be a little more extreme, and we need to completely terminate a for loop. So let's go ahead and build another for loop that we want to print out the numbers and we'll feed it one through 10. i in one through 10. Here we will say if i equals four, break. Now this will completely end the loop, terminate it right where it is. And we'll put in our print statement because we still want things printed. And when we run this... we get the numbers one, two, and three. That's because the first iteration it ran, it was one, if check failed. Second iteration, it failed. Third iteration, if check failed. By the fourth one, it said, okay, i equals four, time to completely end this loop. Again, while you generally want to avoid loops, sometimes they are completely necessary, and the ability to control them will come in very handy.