11.0 Conditional Branching

Way back in Chapter 1, we introduced the idea of control statements, which are statements in an algorithm that tells us under what conditions other actions are carried out. For example, the following plain English algorithm uses a control statement:

Consider the algorithm as a diagram:

You can see at the question "Is the door locked?" that the algorithm branches off into two choices: Yes or No (True or False could also be in place). Programming languages like Python use True or False to tell us if a condition satisfies a specified relationship.

The algorithm accommodates different situations by allowing whoever follows the algorithm to act differently based on their circumstances. For example, we, the algorithm writers, do not know in advance whether our audience for this algorithm will be dealing with locked or unlocked doors, so we write the algorithm such that it can handle either case. Handling multiple cases is called conditional branching because, depending on certain conditions, different algorithm branches will be followed when it is executed.

In this chapter, we will learn how to use conditional branching in Python.