The Potency of else Block
Understand the scope of else block in detail.
We'll cover the following
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
: Thefor
loop running to its completion is a requisite. Theelse
block will run only if thefor
loop does not abort with abreak
statement in between. -
while
: Ifwhile
loop terminates because the condition becomes false, then we can runelse
block. But, what if abreak
statement aborts it? In this case, the control will not be transferred to theelse
block. -
try
: We can useelse
block if no exception is raised in thetry
block. Exceptions in theelse
clause aren’t handled by the precedingexcept
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.
Continue your learning journey with a 14-day free trial.
By signing up, you agree to Educative's Terms of Service and Privacy Policy