Summary: in this tutorial, you’ll learn about the Python for...else statement and how to use it effectively.
Introduction to the Python for…else statement #
In Python, the for statement can have an optional else clause, which you may not be familiar with especially if you’re coming from other languages such as Java or C#.
The following shows the syntax of the for statement with the else clause:
for item in iterables:
# Process item
if condition:
break # Terminate the loop prematurely
else:
# Executed if the loop completes without a breakCode language: PHP (php)In this syntax:
- Python will execute the
elseblock only if theforloop iterates all items in theiterableswithout hitting abreakstatement. - If Python encounters a
breakstatement, it’ll skip theelseblock entirely. - If the
iterableshas no items, Python executes theelseblock immediately.
Unlike the break statement, the continue statement does not end the loop prematurely. Therefore, the else block will execute if the loop completes normarlly.
The following flowchart illustrates logic of the for...else statement: