Exiting Nested Loops Using break
00:00
One important feature of Python loops is that they can be nested. When using break within a nested loop, that is a loop within a loop, the loop containing break is terminated, but only that loop, meaning that surrounding loops continue without interruption, and the loops can be either for or while loops.
00:17 Let’s look at an example back from your side hustle as a game developer, it’s time to be a teacher again. You want to process multiple students’ scores at once now, and they’re stored in a list of lists.
00:29
Define scores as the list of lists. [[90, 30, 80, 100], [180, 95, 87],
00:46
One of the most common ways of dealing with lists of lists is to use nested for loops. You can use scores in a for loop to grab each of these sublists individually, and then use a for loop inside that to grab each student’s scores one by one.
00:59 And this time you just want to see how many students failed even one test. In a situation like this where you might be iterating over many elements of many lists, you definitely want to be as efficient as possible and not waste processing power with extra iterations.
01:13
So of course, you’ll be using break. Start by setting pass_score to 60 and num_failed_students to 0.
01:23
And start the outer loop: for student_scores in scores:. And the only thing inside this outer loop is going to be the inner loop using the student_score variable for score in student_scores:.
01:37
So at this point, score would be an element within one of the student’s scores lists, which is itself one of the lists within the scores nested list: First score will be 90, then 30, etc.
01:47
And now the logic: if score < pass_score: num_failed_students += 1 and break. This checks if the score is a fail, and if so, increments the number of failed students counter by one, then breaks out of the inner loop moving on to the next iteration of the outer loop, that is, the next student’s list of scores.
02:11
The loop runs, and you can check the counter variable num_failed_students. print(f"Number of students who failed the test:
02:25
And it looks like two students had a failing grade. Out of three students, that seems pretty high. Must be a tough class. And that’s break inside of nested loops.
02:35
The most important thing to remember is that it only breaks the innermost loop, letting surrounding loops keep going. So at this point, is there anything else to say about the break, keyword? Else … else, right.
Become a Member to join the conversation.
