Using the else clause on a loop
Python's else
clause can be used on a for
or while
statement as well as on an if
statement. The else
clause executes after the loop body if there was no break
statement executed. To see this, here's a contrived example:
>>> for item in 1,2,3: ... print(item) ... if item == 2: ... print("Found",item) ... break ... else: ... print("Found Nothing")
The for
statement here will iterate over a short list of literal values. When a specific target value has been found, a message is printed. Then, the break
statement will end the loop, avoiding the else
clause.
When we run this, we'll see three lines of output, like this:
1 2 Found 2
The value of three isn't shown, nor is the "Found Nothing" message in the else
clause.
If we change ...
Get Python Essentials now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.