Loading video player…

Exiting a Loop With a Fixed Number of Iterations

Resource mentioned in this lesson: Python for Loops: The Pythonic Way

00:00 We are back in the REPL for this one. In this example, say you’re a teacher and you’re working on evaluating your students based on their test scores. Sounds reasonable. Create a list called scores storing the following integers: 90, 30, 50, 70, 85, 35.

00:17 Consider this a list of one student’s test scores. With a minimum score of 60 to pass, you want to take this list and see how many of the tests received a failing grade.

00:26 You might do it like so. Create a variable to track fails called num_failed_scores and set it to zero: num_failed_scores = 0 and a variable to store the score for a passing grade to compare against, set it to 60: pass_score = 60.

00:43 Then iterate over the list of scores, comparing each against pass_score and incrementing num_failed_scores by one each time a score is less than pass_score.

00:51 for score in scores: if score < pass_score:

00:58 num_failed_scores += 1

01:02 Run the loop and take a look. Print the f-string: Number of failed tests: the value of {num_failed_scores}.

01:13 And this shows the number of failed tests is 3, because three items in scores were less than 60. Good start. But what if what you actually want to do isn’t just count the fails, but flag the student for tutoring if they’ve failed at least two tests. While you could keep the code as is and compare num_failed_scores after the loop runs, that’s inefficient.

01:34 Any processing of the list after a second failure is found is a waste. That makes this a perfect use case for break. Let’s rewrite the loop accordingly.

01:43 First, create a new variable called needs_tutoring set to the string "No". Reset num_failed_scores to 0,

01:54 and there’s no need to reset pass_score since the variable still exists and hasn’t changed. Start the loop in the same way: for score in scores: if score < pass_score: num_failed_scores += 1, but now add a second if condition inline with the first: if num_failed_scores >= 2: set needs_tutoring to Yes and break out of the loop.

02:24 And now run the loop and see the result. Print the f-string: Does the student need tutoring?

02:31 the value of {needs_tutoring}.

02:36 And yes, they do. And you’ll see the value of num_failed_scores is 2 instead of 3. Showing that indeed the loop exited early, and that’s one way you can use break to save a little time and processing power.

02:50 If you’re looking for more practice with for loops, check out “Python for Loops: The Pythonic Way”. Otherwise, you can take a break from being a teacher in the next lesson, where instead you’ll play game developer.

Become a Member to join the conversation.