The Potency of else Block

Understand the scope of else block in detail.

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 not abort with a break statement in between.

  • while: If while loop terminates because the condition becomes false, then we can run else block. But, what if a break statement aborts it? In this case, the control will not be transferred to the else block.

  • try: We can use else block if no exception is raised in the try block. Exceptions in the else clause aren’t handled by the preceding except clauses.

Why use else with these statements? The idea is so simple. It saves us the hassle of setting up control flags and using extra if statements. To prehend this concept, let’s code.

else with for

Below is a simple example demonstrating the use of else with for statement.

Create a free account to view this lesson.

By signing up, you agree to Educative's Terms of Service and Privacy Policy