Introduction
The Python for
–else
clause is an additional, optional syntax Python’s for
loop supports. It enables you to execute a code block after the loop has finished normally, that is, after all the items in the loop’s iterable object had been iterated over. Abnormal, premature termination, due to reasons such as a break
or return
statement, skips that code.
Basic Python for–else Syntax
The Python for
–else
has the usual for
loop syntax with the addition of the else
keyword followed by a colon :
and a code block:
for element in iterable: loop-block else: else-block
for element in iterable
: The usualfor
loop syntax.loop-block
: The code executed for each element in the for loop’s iterable.else-block
: The code that executes after the loop finishes normally.
Using the else Clause With for Loops
The lesson about the break
keyword introduced the code example below.
Example:
dogs = ["Scooby-Doo", "Snoopy", "Goofy", "Clifford", "Astro"] num_of_treats = 3 for dog in dogs: if num_of_treats == 0: break print(f"{dog} gets a treat. Woof!") num_of_treats -= 1
Output:
Scooby-Doo gets a treat. Woof! Snoopy gets a treat. Woof! Goofy gets a treat. Woof!
As you may recall from that lesson, the example is about giving dogs some treats. The number of treats is limited, and not every dog may get one. The for
loop iterates through the dogs (given by the dogs
list), but if the treats run out, a break
statement exits the loop and no more treats are given.
Now, additional requirements for the program came in, as follows:
- Print an appropriate alert if the treats run out before all the dogs are given one.
- Print an appropriate statement if all dogs were given a treat which includes include the number of treats remaining.
We’ll implement the first requirement by adding a print()
statement right before the break
in the same code block. We will implement the second requirement with an else
clause.
Example:
dogs = ["Scooby-Doo", "Snoopy", "Goofy", "Clifford", "Astro"] num_of_treats = 10 for dog in dogs: if num_of_treats == 0: print("The treats have run out! Please order some more.") break print(f"{dog} gets a treat. Woof!") num_of_treats -= 1 else: print(f"Every dog got a treat. There are {num_of_treats} treats remaining. Good job!")
Output:
Scooby-Doo gets a treat. Woof! Snoopy gets a treat. Woof! Goofy gets a treat. Woof! Clifford gets a treat. Woof! Astro gets a treat. Woof! Every dog got a treat. There are 5 treats remaining. Good job!
As you can see in the example above, the first requirement to print an alert when the treats run out, is implemented by the print()
statement on line 6. The second requirement to print a message when all dogs have been successfully given a treat, is implemented by the else
clause and code block on lines 10 and 11. The code block of the else
clause executes only if all dogs have been iterated through and the break
statement on line 7 has not been executed.
Let’s see what happens when the break
does execute. To do this we’ll change the initial number of treats to 2.
Example:
dogs = ["Scooby-Doo", "Snoopy", "Goofy", "Clifford", "Astro"] num_of_treats = 2 for dog in dogs: if num_of_treats == 0: print("The treats have run out! Please order some more.") break print(f"{dog} gets a treat. Woof!") num_of_treats -= 1 else: print(f"Every dog got a treat. There are {num_of_treats} treats remaining. Good job!")
Output:
Scooby-Doo gets a treat. Woof! Snoopy gets a treat. Woof! The treats have run out! Please order some more.
The only code change in the example above from the previous one is on line 3, where the number of treats is set to 2. But since there are five dogs, the treats run out, triggering the break
on line 7. Because the loop does not terminate normally, the code block under the else
is not executed.
The Alternative to the for Loop else Clause
The else
clause exists because it can lead to less repetition and cleaner code. If we couldn’t use the else
clause with the for loop, we would have to check the number of remaining treats again after the loop.
dogs = ["Scooby-Doo", "Snoopy", "Goofy", "Clifford", "Astro"] num_of_treats = 2 for dog in dogs: if num_of_treats == 0: print("The treats have run out! Please order some more.") break print(f"{dog} gets a treat. Woof!") num_of_treats -= 1 if num_of_treats != 0: print(f"Every dog got a treat. There are {num_of_treats} treats remaining. Good job!")
The example above has the same output as the previous one, but now it uses an if
statement and a code block after the for loop on lines 11 and 12, instead of the else
clause.
Summary & Reference for the Python for-else Clause
The Python for
–else
clause is an optional addition to the for
loop. It executes a code block after the loop, if it finishes normally, which means after all the items in the loop’s iterable are iterated over.
Abnormal, premature loop termination, due to reasons such as a break
or return
statement, skips that code.
Here is the basic for
–else
syntax:
for element in iterable: loop-block else: else-block