Detect Completion with else Clause
In this step, you will learn how to use the else
clause with a for
loop to detect if the loop completed without encountering a break
statement. This can be a clean and elegant way to execute code only when a loop finishes normally.
Let's create a Python file named else_example.py
in your ~/project
directory using the VS Code editor.
## Filename: else_example.py
numbers = [1, 2, 3, 4, 5]
for number in numbers:
if number > 5:
print("Found a number greater than 5")
break
print(number)
else:
print("No number greater than 5 was found")
In this code:
- We iterate through the list of numbers.
- If we find a number greater than 5, we print a message and
break
out of the loop.
- The
else
clause is associated with the for
loop. It will be executed only if the loop completes without encountering a break
statement.
Now, let's run the script using the following command in the terminal:
python else_example.py
You should see the following output:
1
2
3
4
5
No number greater than 5 was found
The else
clause was executed because the loop completed without finding any number greater than 5.
Now, let's modify the numbers
list to include a number greater than 5:
## Filename: else_example.py
numbers = [1, 2, 3, 4, 5, 6]
for number in numbers:
if number > 5:
print("Found a number greater than 5")
break
print(number)
else:
print("No number greater than 5 was found")
Run the script again:
python else_example.py
You should see the following output:
1
2
3
4
5
Found a number greater than 5
In this case, the else
clause was not executed because the loop was terminated by the break
statement.
The else
clause with a for
loop provides a concise way to execute code when a loop completes normally, without being interrupted by a break
statement. This can make your code more readable and easier to understand.