Search⌘ K
AI Features

The Potency of else Block

Understand the versatile use of the else block in Python beyond if statements. Learn how else integrates with for and while loops as well as try statements to control program flow effectively when loops complete normally or no exceptions occur. This lesson helps you write clearer code by eliminating unnecessary flags and conditions.

An unacknowledged feature

You may be startled to learn that the scope of the else block exists beyond the if statement. The else clause also works with the for, while and try statements.

Python follows a specific code of behavior when extending the else scope. Let’s get acquainted with it before running a few examples.

  • for: The for loop running to its completion is a requisite. The else block will run only if the for loop does ...