Flow Control (Also Called Control Flow) – ‘if’, ‘if-else’, and ‘else-if’ Statements
Flow Control is necessary for all programs. The flow control is done using the if, if-else, and else-if statements. These statements change the program flow based on the results of the previous instruction or external inputs.
What is Flow Control and Why It Is Important
The CPU executes the instructions sequentially in the same order as written in the program. This means the programs do not have the flexibility to change the program flow based on the results of the previous instruction or external inputs.
In this chapter, you will learn about program flow control. You will learn what flow control is and why flow control in programming is necessary.
In all programs, there is usually a need to change the program flow to execute either one block of the code or a different block of code based on the result of the test of a condition. The condition may be one of the conditions (comparison operators or logical operators) discussed in the Operators and Operands Chapter.
The condition may also be due to an external input.
If the result of the test of the condition is ‘yes’ (also called ‘true’), the program takes one program branch and executes the block of code in that branch. If, on the other hand, the result of the test is ‘no’ (also called ‘false’), the program flow takes an alternative branch and executes the block of code in the alternative branch.
Program Flow Control Test Conditions
Three flow control statements are used as test conditions. These control statements change the program execution flow depending result of the test conditions.
The control statements used to test the conditions are:
if’, ‘if-else’, and ‘else-if’.
These statements make the programs very powerful since they let the program make decisions on what branch of code to execute next based on certain tests specified in the if, if-else, and else-if statements.
These test conditions may be the result of an arithmetic computation, a comparison operation result, or a logical operation result.
The if, if-else, and else-if statements may also test an external input such as temperature measured by a sensor, and change the program flow based on the sensor value reading.
In some other instances, the external input may be the data entered by the user from the keyboard that may change the program flow.
Home Thermostat – A Real Life Example of Flow Control
As an example of program flow control caused by the sensor reading, we will use a home thermostat.
In the next paragraph, we explain how an external sensor directs the program to choose a branch of the code versus an alternate branch of code.
If the temperature sensor in your home thermostat senses the temperature to be below a certain set temperature, the thermostat program will direct the heating furnace to turn on the heat.
On the other hand, if the thermostat temperature sensor senses the room temperature to be above the set temperature, the program will direct the air-conditioning unit to turn on cooling.
To explain the flow control concepts, we will write programs using data from our solar system.
For other examples of flow control, we will write programs that show how program flow control is used in the operation of thermostats in home heating/cooling systems.
NOTE: The if, if-else, and else-if statements combined with loops make the programs very useful for real-life applications. We will discuss the loops on the “Loops in Python” page.
The if Conditional Test For Program Flow Control
The if statements involve testing for a condition. The following is the if statement syntax.
if
condition = true:
execute this block of statements
If the test specified in the condition is tested to be ‘True’, the block of code after the if statement is executed. If the test specified in the condition test does not pass (i.e. ‘False’), the block of code following the true block is not executed.
Note the if
statement condition must end with colon (:).
Let us explore the if
statement usage with a couple of program examples that use the comparison operator condition test.
The first program example is from a previous program about your friends’ age. For the second example, we use the solar system that we used in the previous chapters.
ROGRAM EXAMPLE: if STATEMENT USAGE
>>> # Define three variables, Michael_age, Steve_age, and Alice_age
>>> # and assign them values 7, 8, and 6 respectively
>>> Michael_age = 7
>>> Steve_age = 8
>>> Alice_age = 6
>>> # Compare Michael_age to Steve_age for the ‘less than’ test condition,
>>> # then execute the next statement if condition specified in the test is ‘yes’ (‘true’)
>>> if Michael_age < Steve_age:
print('Michael is younger than Steve') #1)
Michael is younger than Steve
>>> Now check ‘greater than’ compare test condition.
>>> if Steve_age > Alice_age:
print('Steve is older than Alice') #2)
Steve is older than Alice
>>>
For the program explanation below, refer to the line numbers in the program above.
1) Since Michael is younger than Steve, the if test condition evaluates to true. Therefore, the next line of the code is executed and the program prints ‘Michael is younger than Steve’.
2) In line 2) the if condition tests whether Steve is older than Alice. Since Steve is older than Alice, the if statement evaluates to true. Therefore the next line of the code is executed and the program prints ‘Steve is older than Alice’.
The if Condition Usage – The Solar System Example
Let us write another simple program using solar system data to illustrate the if
statement usage. For the solar system example, we will write a program that compares the number of moons for various planets in our solar system.
The information about the moons in the solar system is at the end of the Python Data Types Chapter in the section Enrichment: Astronomy Related.
PROGRAM EXAMPLE: If STATEMENT USAGE – SO;AR SYSTEM EXAMPLE
>>> # Define variables for number of moons for various planets
>>> # and assign them values.
>>> number_of_Jupiter_moons = 79
>>> number_of_Neptune_moons =14
>>> number_of_Uranus_moons = 27
>>> if number_of_Jupiter_moons > number_of_Uranus_moons:
print('Jupiter has more moons than Uranus')
Jupiter has more moons than Uranus
>>> if number_of_Neptune_moons < number_of_Jupiter_moons:
print('Neptune has less moons than Jupiter')
Neptune has less moons than Jupiter
>>>
if-else Conditional Test
The if
statement executes a block of statements if the result of the test specified in the condition is evaluated to be true (yes), but it does not specify what to do if the condition is evaluated to be false.
The if-else
statement tells the program what to do in case the test of the condition is evaluated to be false (no).
The if part of the if-else
statement specifies the block of code to be executed for condition = true; the else
part of the if-else
test condition specifies a different block of code to be executed if the result of the test of the condition is false.
if-else
statement syntax:
if
condition is true:
execute this block of statements
else:
execute this different block of statements
How Does if-else Conditional Test Works
For explaining the if-else
test condition, we will extend the friends’ age program example and add the else branch
In the Program Example below, the Program-1 specifies a comparison operator test that results in the if
test condition evaluating to true. We will see that the program executes the if branch and skips the else
branch.
In Program-2, the comparison operator test is such that the if
test condition evaluates to false. We will see that the program skips the if
branch and executes the else
branch.
PROGRAM EXAMPLE: if-else TEST CONDITION USAGE
>>> # Define three variables, Michael_age, Steve_age, and Alice_age
>>> # and assign them values 7, 8, and 6 respectively.
>>> Michael_age = 7
>>> Steve_age = 8
>>> Alice_age = 6
>>> # PROGRAM-1:
>>> Compare Michael_age to Steve_age. In the code below, the test condition
>>> # for if statement is true. The program takes the if branch and
>>> # skips the else branch.
>>> if Michael_age < Steve_age:
print('Michael is younger than Steve.') # Program takes the if branch.
else:
print('Michael is older than Steve.')
Michael is younger than Steve.
>>> # PROGRAM-2:
>>> # Here the test condition in the if statement is false.
>>> # So, the program takes the else branch.
>>> if Steve_age < Alice_age:
print('Steve is younger than Alice.')
else:
print('Steve is older than Alice.') # Program takes the else branch.
Steve is older than Alice.
>>>
Let’s now write a more complex program using the if-else
statement. We will use the thermostat that we discussed in an earlier section.
The if-else Conditional Test – Thermostat Example
In your home, you may have a heating/cooling system that has a thermostat with ‘cool’ and ‘heat’ controls.
Let us assume you feel comfortable at a temperature of 71°F.
If the temperature in the home falls below 71°F, you would like the thermostat to turn on the heating furnace; else if the temperature in the home is greater than 71°F, you would like to turn on air-conditioning (cooling).
The above sentence explains the functionality of the if-else
statement.
In the program below, we define a variable called ‘temp_home’ and assign it an initial value of 65°F. We define another variable called ‘temp_set’ and assign it a value of 71°F. This is the temperature the thermostat is set at and is the desired temperature.
PROGRAM EXAMPLE: if-else PROGRAM USING THERMOSTAT AS AN EXAMPLE
>>> # if-else program example
>>> Program Example-1
>>> temp_home = 65 # Current home temperature.
>>> temp_set = 71 # Temperature the thermostat is set to desired temperature.
>>> # Since home temperature is less than the temperature
>>> # set on the thermostat, the program will skip the
>>> # if statement and will execute the else statement.
>>> if temp_home > temp_set:
print('Too hot. Turn on cooling') #1)
else:
print('Too cold. Turn on heat')
Too cold. Turn on heat
>>> Program Example-2
>>> # Now suppose the day becomes very hot and the home temperature
>>> # rises to 80 degrees Fahrenheit. Now we will verify that the
>>> # program takes the if branch.
>>> temp_home = 80 # Temperature in the home is 80.
>>> if temp_home > temp_set:
print('Too hot. Turn on cooling') #2)
else:
print('Too cold. Turn on heat')
Too hot. Turn on cooling
>>>
Detailed Explanation of the Program
For the program explanation below, refer to the lines with comments numbers above.
1) In Program Example-1, temp_home = 65 and temp_set = 71.
Since the ‘temp_home’ is less than ‘temp_set’, the if test condition evaluates to false. Therefore, the program skips the if statement and executes the else branch of code. Therefore, it prints ‘Too cold. Turn on heat’
2) In Program Example-2, temp_home = 80 and temp_set = 71. Therefore, the thermostat detects that temp_home > temp_set.
Since the ‘temp_home’ is greater than ‘temp_set’, the if test condition evaluates to true. Therefore, the program executes the if branch of the code and skips the else branch, and prints ‘Too hot. Turn on cooling’.
else-if (elif) Conditional Test For Program Flow Control
You saw in the previous sections that the if
statement makes the program execute a block of code if the test specified in the if
statement is true (yes).
You also saw that the if-else
statement executes a block of code in case the test of the if
condition is true (yes) and an alternate block of code in case the test of the if
condition is false (no). That is, there are just two options. Putting it another way, there are a total of two alternate blocks of code, one of which is executed based on the result of a test condition.
So, what would the programmer do if the application requires many alternatives?
else-if (elif
for short) statement lets us extend the if
statement for as many numbers of conditions as we like. Whereas the if-else
statement allows the program to have just two options (true or false), the elif
statement allows the programmer to have many elif
statements in the same statement.
The else-if Statement Decision Flowchart
The decision tree of the if, else-if, and else test conditions are in the above flowchart.
More information on the if, else-if, and else test conditions is at this link and this link.
Note: There is always a colon (:) at the end of if
and else
statements. After the colon (:), the next line is indented automatically by Python. Do not backspace it, otherwise, you will get a syntax error. After you write the print statement, Python will indent the next line too. Make sure to backspace so that the next line starts at the far left of the screen.
The following program illustrates the use of the elif
test condition. The simple program below uses the solar system facts to illustrate the use of the else-if (elif) condition test.
PROGRAM EXAMPLE: else-if TEST CONDITION USAGE
>>> # This program illustrate how else-if statement can be used for multiple test conditions.
>>> # The following are distances of solar system planets from Sun in millions of miles.
>>> Mercury = 37
>>> Venus = 65
>>> Earth = 93
>>> Mars = 140
>>> Jupiter = 484
>>> Saturn = 884
>>> Uranus = 1786
>>> Neptune = 2790
>>> # Test if Mercury planet is farther from Sun than Venus.
>>> if Mercury > Venus:
print('Mercury is farther to Sun than Venus.') # Test result is false. Instruction is skipped.
elif Venus > Earth:
print('Venus is farther from Sun than earth.') # Test result is false. Instruction is skipped.
elif Earth > Mars:
print('Earth is farther from Sun than Mars.') # Test result is false. Instruction is skipped.
elif Neptune > Uranus:
print('Neptune is farther from Sun than Uranus.') # Test result is true. Instruction is executed.
else:
print('This is enough Comparison operator testing')
Neptune is farther from Sun than Uranus.
>>>
More else-if Test Condition Use Examples
Now we will use a slightly more complex program to illustrate the use of the else-if condition test for program flow control. The program uses the thermostat example. The in-line comments explain the operation of the program.
PROGRAM EXAMPLE: else-if PROGRAM – USING THERMOSTAT AS AN EXAMPLE
# Example of the use of elif statement with many elif.
# Define a variable ‘temp_home’ (initial home temperature) and assign a value of 65 degrees.
temp_home = 65
temp_home_1 = 70 # Define temp_home_1 after the heating has been ON for some time.
temp_home_2 = 74 # Define temp_home_2 after the heating has been ON for a long time.
# Define a variable ‘temp_set’ (thermostat setting) and assign a value of 73 degrees (desired temperature).
temp_set = 73
# temp_home < temp_set. Comparison operation evaluates false. The if branch is skipped.
if temp_home > temp_set:
print('Home temperature of ', temp_home, ' is too hot; turn on cooling.')
# Heating has been ON for some time. temp_home_1 rises to 70.
# Check if home temperature has reached thermostat setting.
elif temp_home_1 > temp_set: # First elif. This test evaluates to false. Skips this statement.
print('Home temperature of ', temp_home_1, ' is too hot, turn on cooling.')
# Heating has been ON for a long time. temp_home_2 rises to 74.
# Continue checking if the home temperature has reached thermostat setting.
elif temp_home_2 < temp_set: # Another elif. This condition evaluates false.
print('Home temperature of ', temp_home_2, ' is too cold; turn on heat.') # Statement skipped.
else:
print('Home temperature of ', temp_home_2, ' is too hot; turn on cooling.') # Statement executed.
PROGRAM OUTPUT:
Python 3.8.1 (tags/v3.8.1:1b293b6, Dec 18 2019, 22:39:24) [MSC v.1916 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
============= RESTART: C:/Users/User_name/Python_scripts/python_elif.py =============
Home temperature of 74 is too hot; turn on cooling.
>>>