Locked learning resources

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

Unlock This Lesson

Locked learning resources

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

Unlock This Lesson

Writing Advanced Loops With else

00:00 There exists an underused and to many developers unknown feature of Python loops. One that makes them distinct from those found in other programming languages.

00:09 What is it? They can be used with an optional else clause. This else clause executes if its corresponding loop completes without encountering a break.

00:18 I know else sounds like it should be related to some sort of false condition, but it’s not. It only runs if the loop finishes execution normally.

00:27 else can be used both with for and while loops. It’s included in this course because it’s actually a great complement to break. else only runs if break doesn’t.

00:37 Let’s open the REPL and take a closer look. One more time, let’s start by creating a list of scores. scores = [90, 30, 50, 70, 85, 35] Once again, you want to see if this student needs tutoring.

00:52 Have they failed at least two tests? Instead of what we did before, using a separate variable saying yes or no, you can implement the logic using break and an else clause. As setup, set num_failed_scores to 0 and pass_score to 60.

01:10 And iterate over scores: for score in scores:

01:15 if score < pass_score: num_failed_scores += 1

01:22 Again, this tracks how many failing scores have been encountered. And if num_failed_scores >= 2:

01:31 Here, print("The student needs tutoring.") and break.

01:38 And here’s where you can use an else block. Add an else block that will run if the loop finishes without hitting break. And note that else should line up with for. else: print("The student doesn't need tutoring.")

01:54 Run the loop. Of course, the student needs tutoring because there were at least two values less than 60 in the list of scores. You achieved effectively the same logic as the previous example, but without the need for an extra needs_tutoring variable. Not bad.

02:11 So that’s else. It’s an elegant way to run code based on a loop’s exit conditions. I’m sure you’re already imagining all sorts of ways you can use this combination of break and else to write cleaner, more effective for loops.

02:23 If you want more practice, I recommend trying this loop with different lists of scores. Then watch the value of num_failed_scores and see which print statement runs.

02:32 But as for this course, it’s time to close the loop in the summary.

Become a Member to join the conversation.