Readings: [1.7]

Introduction

There are alternate options to branching. The if statement executes code based on a comparison condition. The code then continues with the next statement after the if block concludes. In some cases, however, it is helpful to execute an alternate block of code OR to make additional comparisons to select the appropriate block of code to run. These are the reasons for the else and elif clauses to the if statement.

Else

The else statement cannot exist by itself, it can only exist as a continuation of an if statement. In this respect, the else clause is set at the same indent level as its corresponding if statement. As such, it ends the code block under the if statement and starts another indented code block.

If the if condition evaluates to True, the code block below it is executed, and the else clause and code block are skipped. In this case, the if statement is terminated at the next statement at the same indent level after the else block. If the if condition evaluates to False, the entire block below it is skipped. If there is an else statement, the code block below it is executed. The diagram below illustrates these program flows.

IF-ELSE Program Flow

IF-ELSE Program Flow

ELIF

The elif statement is another possible continuation of an if statement. The elif clause includes another comparison condition. This is essentially adding multiple if statments together.

The elif clause cannot stand on its own, it must exist as a continuation of an if statement. There can be many elif clauses. The first true condition executes the block below it and then anything after it is skipped, and the program continues with the next statement after the entire if super block.

It is also possible to include an else clause at the end of one or more elif clauses. This is basically saying "if nothing else worked, do this". The else clause is not required, which means if none of the conditions were true, no code in the entire block would be executed.

In all cases, if any condition is true and a corresponding code block is executed, everything else in the super code block is skipped. It is important for the developer to consider the order in which the conditions should be evaluated, to make sure the program flow works as intended. The diagram below illustrates how an IF-ELIF-ELSE block works.

IF-ELIF-ELSE Program Flow

IF-ELIF-ELSE Program Flow


Keywords Covered in this Article