Book Image

Python Essentials

By : Steven F. Lott
Book Image

Python Essentials

By: Steven F. Lott

Overview of this book

Table of Contents (22 chapters)
Python Essentials
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

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 the target value in the if statement from two to a value that won't be seen (for example, zero or four), then the output will change. If the break statement is not executed, then the else clause will be executed...