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.
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: Theforloop running to its completion is a requisite. Theelseblock will run only if theforloop does not abort with abreakstatement in between. -
while: Ifwhileloop terminates because the condition becomes false, then we can runelseblock. But, what if abreakstatement aborts it? In this case, the control will not be transferred to theelseblock. -
try: We can useelseblock if no exception is raised in thetryblock. Exceptions in theelseclause aren’t handled by the precedingexceptclauses.
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.
You can see that if 5 is found in the list, the for loop will abort. If not, which is true in this case, the loop will terminate to its completion, and else (see line 8) will be executed. That’s why the program generates the ValueError.
else with while
Run the following program, to grasp how else works with while.
This program is similar to the above one, in a sense, they are both doing the same thing with just a single difference that this time we are using the while loop. Here, the program also generates ValueError because the else block gains control as the loop aborts when condition (counter < len(l)) becomes false.
else with try
Before trying else with try, how about doing it without else first? Just give the following snippet a once-over:
try:
print(x)
x += 1
except:
print("Variable not defined.")
The statement x += 1 will only execute if no exception is generated. It means that this statement is here for no good reason.
For clarity purposes, we can bind else with try. Let’s do it
So you notice that here exception was generated as x was not declared. Due to which else clause didn’t get the control.