4. Control Statements

Control statements are also called if/else statements or conditional statements. These types of statements control the flow of your program based on boolean logic, expressions, values, evaluations or outcomes. The intelligence in computational intelligence, machine learning or artificial intelligence are based on these control statements. For example, an intelligent self-driving car may have a control flow as follows:

  • if the traffic light is yellow, then slow down

  • if the traffic light is red, then stop

  • if the traffic light is green, then go

Control statements are how computers (and, most likely, even humans) make categorical decisions and take actions based upon those decisions.

4.1. if

The most basic form of if/else statements comes when you are only using if. Below, you have the state of the traffic light (which is yellow), and you want to test to see if the traffic light is yellow. If the traffic light is yellow, you print slow down.

1traffic_light = 'yellow'
2
3if traffic_light == 'yellow':
4    print('slow down')

There is a lot going on with just this simple if/else statement. First, note that after if we have a comparison that evaluates to true or false: traffic_light == 'yellow'. This comparison is using the equality comparison operator == which must evaluate to True or False. The way to read this comparison naturally is: is the traffic light yellow?

Second, note the use of the block operator : after the comparison. This block operator signals that a block of code is going to follow. A block of code is just a sequential set of statements that are indented at the same level. Which leads us to the third point.

Third, did you observe that we indented the print statement in the next line following the if statement? This indentation says that the print statement belongs to the if statement. Only if the comparison evaluates to True do we execute the print statement. If we did not indent the print statement, then there is nothing to do if the traffic light is yellow, and this is also a syntax error.

1traffic_light = 'yellow'
2
3# not having a block of statement below if results in an error
4if traffic_light == 'yellow':

If we did not know yet what to do if the traffic light is yellow, then we can use the pass keyword under the if statement.

1traffic_light = 'yellow'
2
3# using pass under if is ok, if we do not yet know what to do
4if traffic_light == 'yellow':
5   pass

If we needed to do multiple things when the traffic light is yellow, we can supply multiple statements.

1traffic_light = 'yellow'
2
3if traffic_light == 'yellow':
4   print('take foot off accelerator pedal')
5   print('start pressing on brake pedal')
6   print('stay focused')

4.1.1. Exercise

We have the state of the weather, which can be rainy or sunny.

  • If it is rainy, then we must advise a person to wear a rain jacket.

  • If it is sunny, then we must advise a person to wear shorts.

Write simple programs to store the weather’s state and a simple if/else statement to advise a person what to do.

Solution.

1weather = 'rainy'
2
3if weather == 'rainy':
4   print('wear a rain jacket')
1weather = 'sunny'
2
3if weather == 'sunny':
4   print('wear shorts')

4.2. if-else

When we are testing a condition, we know we can provide a block of statements for the computer to do if that condition evaluates to True. But what if the condition evaluates to False and we still want to provide a block of statements for the computer to do? How do we write an if/else statement for this case?

Below, we have two integers a and b, and we want to do something when a is greater than b and something else when that condition fails (evaluates to False). This situation would require us to combine the else statement with the if.

Note

Notice how the else comes after the if? Notice also how the else is followed by a :? Lastly, the else does not need any boolean expression to be evaluated. The else part of the if-else statement is called the catch-all case.

1a = 10
2b = 9
3
4if a < b:
5    print('a < b')
6else:
7    print('a >= b')

In an if-else statement, when the condition in the if part evaluates to true, the code block underneath it is executed and the code block under the else is ignored. Likewise, when the condition in the if part evaluates to false, the code block underneath it is ignored and the code block under the else is executed.

4.2.1. Exercise

Write a program to instruct the user to wear a rain coat and bring an umbrella if the weather is rainy, otherwise, to wear shorts and sunglasses if it’s sunny.

1weather = 'rainy'

Solution.

1weather = 'rainy'
2
3if weather == 'rainy':
4   print('wear rain jacket')
5   print('bring umbrella')
6else:
7   print('wear shorts')
8   print('wear sunglasses')

We could of tested for sunny weather too.

1weather = 'rainy'
2
3if weather == 'sunny':
4   print('wear shorts')
5   print('wear sunglasses')
6else:
7   print('wear rain jacket')
8   print('bring umbrella')

4.3. if-elif-else

We can test for multiple conditions using if-elif-else. The elif is Python’s way of saying else if.

1a = 9
2
3if a < 10:
4    print('a < 10')
5elif a < 20:
6    print('a < 20')
7else:
8    print('a >= 20')

In an if-else statement, the if must always come first, the else must always come last, the elif must always be in the middle and we can have any number of elif. Look at the example below.

 1a = 9
 2
 3if a < 5:
 4   print('a < 5')
 5elif a < 10:
 6   print('a < 10')
 7elif a < 15:
 8   print('a < 15')
 9elif a < 20:
10   print('a < 20')
11else:
12   print('a >= 20')

4.3.1. Exercise

A percentage score on a test will be assigned a letter grade according to the following.

  • [100, 90] is A

  • [89, 80] is B

  • [79, 70] is C

  • [69, 60] is D

  • [59, 0] is F

A person has a 84 on a test. Write a if-else statement to assign (or map) this score to a letter grade.

  • Hint: use boolean logic

Solution.

 1score = 84
 2
 3if score <= 100 and score >= 90:
 4   print('A')
 5elif score <= 89 and score >= 80:
 6   print('B')
 7elif score <= 79 and score >= 70:
 8   print('C')
 9elif score <= 69 and score >= 60:
10   print('D')
11else:
12   print('F')

4.4. Multiple comparison in if-else

When evaluating conditions, you can use multiple comparisons to test for True or False.

1a = 10
2
3if 0 <= a < 5:
4    print('[0, 5)')
5elif 5 <= a < 8:
6    print('[5, 8)')
7else:
8    print('[8, +Infinity)')

4.4.1. Exercise

Modify the code below to use multiple comparison instead of boolean logic.

 1score = 84
 2
 3if score <= 100 and score >= 90:
 4   print('A')
 5elif score <= 89 and score >= 80:
 6   print('B')
 7elif score <= 79 and score >= 70:
 8   print('C')
 9elif score <= 69 and score >= 60:
10   print('D')
11else:
12   print('F')

Solution.

 1score = 84
 2
 3if 90 <= score <= 100:
 4   print('A')
 5elif 80 <= score <= 89:
 6   print('B')
 7elif 70 <= score <= 79:
 8   print('C')
 9elif 60 <= score <= 69:
10   print('D')
11else:
12   print('F')

4.5. Nested if-else

if-else statements could also be nested as shown below.

 1a = 9
 2
 3if a > 20:
 4    print('a > 20')
 5elif a > 10:
 6    print('a > 10')
 7else:
 8    if a > 5:
 9        print('a > 5')
10    else:
11        print('a <= 5')

Warning

Nested if-else statements produces cyclomatic complexity. Try to stay away from nested if-else statements when possible.

4.5.1. Exercise

For some reason, John likes to do certain sports dependent on what the weather is like and what the day is. John looks at the weather in terms of sunny or rainy, and he looks at the day in terms of whether it’s odd or even.

  • If it’s sunny and an even numbered day, John likes play basketball.

  • If it’s sunny and an odd numbered day, John likes play baseball.

  • If it’s rainy and an even numbered day, John likes play football.

  • If it’s rainy and an odd numbered day, John likes play soccer.

Write a program to tell John what to do if the given weather and day is specified.

1weather = 'sunny'
2day = 2

Solution.

 1weather = 'sunny'
 2day = 2
 3is_even = day % 2 == 0
 4
 5if weather == 'sunny' and is_even:
 6   print('basketball')
 7elif weather == 'sunny' and not is_even:
 8   print('baseball')
 9elif weather == 'rainy' and is_even:
10   print('football')
11else:
12   print('soccer')