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 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.

Python 3.10.4
l = [1, 2, 3, 4]
for i in l:
if i == 5:
break
# If item not found
else:
raise ValueError('Item not found!')

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.

Python 3.10.4
l = [1, 2, 3, 4]
counter = 0
while counter < len(l):
if l[counter] == 5:
break
counter += 1
# If item not found
else:
raise ValueError('Item not found!')

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

Python 3.10.4
try:
print(x)
except:
print("Variable not defined.")
# If no exception is raised
else:
x += 1

So you notice that here exception was generated as x was not declared. Due to which else clause didn’t get the control.