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.

The While Loop Else Clause

This lesson covers the while-loop-else-clause, which is unique to Python. The else-block is only executed if the while-loop is exhausted. You don’t know what that means? Check out this lesson to find out! Furthermore, you can find two examples below, which you can copy-paste and run to get a sense of what’s happening.

Python
n = 5
while n > 0:
    n = n - 1
    if n == 2:
        break
    print(n)
else:
    print("Loop is finished")
Python
n = 5
while n > 0:
    n = n - 1
    if n == 2:
        continue
    print(n)
else:
    print("Loop is finished")

00:00 Now, there is one more thing we can add to our while loop, and that is this else statement. Now, this is actually unique to Python. Not a lot of other while loops in other languages are going to have something like this.

00:13 But what it does is it gives us a way to execute a block of code right after the while loop is exhausted. Now you could be thinking, “Well, why don’t I just do what I did before and add a statement to the end of my while loop?” You can. However, there’s one weird thing about the else statement and that is that it’s only going to happen if the while loop is exhausted, meaning that if I were to use something like break, it would not actually print. Let’s look at an example.

00:44 We’re going to use the same one that we just did, but for a minute we’re just going to go back to break so we can see what happens.

00:53 If I run this code,

00:57 I see that I did not actually print 'Loop is finished' like I did before, and that’s because, remember, this else statement is only going to execute if it is exhausted. So if I were to go back to continue, this is actually going to continue on until that loop is exhausted, so it should print 'Loop is finished'. Let’s see if that’s true.

01:22 There we go! Now, like I said, this is going to give you the same outcome as if you didn’t use this else statement. The one thing to note is that if you do use a break statement, that else is not going to be executed. All right, so that’s going to pretty much wrap up the continue and break statements.

01:44 We’re going to move on to infinite loops now.

byralph on Oct. 31, 2022

Hello, great course. Which tool do you use for presenting your code? Thank you.

Become a Member to join the conversation.