Skip to content
Home » The else Statement in WHILE and FOR Loops

The else Statement in WHILE and FOR Loops

Spread the love

Today we’ll be talking about the else statement used in loops.

else statement in loops

You definitely know the else block from conditional statements where you use it to give an alternative in case the condition is not met. In other words, the else block is used to set the default branch of the conditional structure. But you can also use else in loops, both while loops and for loops.

The else statement is usually combined with the break statement. Actually, whether it’s taken into consideration at all by the program depends on whether there also is a break statement in the code. The else statement is run whenever the break statement is not executed. If the break statement is executed, the else statement isn’t.

The else Statement in a while Loop

In the first example break will be executed, which means else won’t:

# break will be executed
loop_counter = 1

while loop_counter < 5:
    print(f"In the loop - iteration {loop_counter}")
    if loop_counter == 3:
        print("breaking from the loop...")
        break
    loop_counter += 1

# so else will not be executed
else:
    print(f"Congrats! You completed the loop in {loop_counter} steps.")

If you run this program, you will get the following output:

In the loop - iteration 1
In the loop - iteration 2
In the loop - iteration 3
breaking from the loop...

And now, in the other example, break will not be executed. This means that the program will execute the else block:

# break will not be executed
loop_counter = 1

while loop_counter < 5:
    print(f"In the loop - iteration {loop_counter}")
    if loop_counter == 5:
        print("breaking from the loop...")
        break
    loop_counter += 1

# so else will be executed
else:
    print(f"Congrats! You completed the loop in {loop_counter - 1} steps.")

Now when you run the program the output is:

In the loop - iteration 1
In the loop - iteration 2
In the loop - iteration 3
In the loop - iteration 4
Congrats! You completed the loop in 4 steps.

Your Panda3D Magazine

Make Awesome Games and Other 3D Apps

with Panda3D and Blender using Python.

Cool stuff, easy to follow articles.

Get the magazine here (PDF).

else in a for Loop

In the examples above we were using the while loop. But it also works for for loops. Here are similar examples with a for loop. Again, let’s start with a program where break will be executed and else won’t:

# break will be executed
letters = ['a', 'f', 'h', 'b']

for letter in letters:    
    if letter == 'h':
        print("Something went wrong! Breaking from the loop...")
        break
    print(f"printing {letter}... - success")

# so else will not be executed
else:
    print("Congrats! You managed to loop over all the letters.")

The output is:

printing a... - success
printing f... - success
Something went wrong! Breaking from the loop...

Python Jumpstart Course

Learn the basics of Python, including OOP.

with lots of exercises, easy to follow

The course is available on Udemy.

And, just as with the while loop before, let’s have a look at another example where break is not executed. Here the else part will be executed:

# break will not be executed
letters = ['a', 'f', 'h', 'b']

for letter in letters:    
    if letter == 'z':
        print("Something went wrong! Breaking from the loop...")
        break
    print(f"printing {letter}... - success")

# so else will be executed
else:
    print("Congrats! You managed to loop over all the letters.")

Here’s the output:

printing a... - success
printing f... - success
printing h... - success
printing b... - success
Congrats! You managed to loop over all the letters.

Blender Jumpstart Course

Learn the basics of 3D modeling in Blender.

step-by-step, easy to follow, visually rich

The course is available on Udemy and on Skillshare.

else is not very frequently used in loops, so if you don’t know how to use it, you will probably be able to achieve what you need in different ways. However, it’s always good to understand how it works when you come across it in someone else’s code. And with time you may want to use it yourself more and more, because it’s another nice feature of Python you have at hand.

Here’s the video version:


Spread the love

Leave a Reply