3  Making Choices and Controlling Program Flow

  1. Questions:
  1. Objectives:
  1. Keypoints:

How can we use Python to automatically recognize differences in data such that it can change what code is run depending on the data and take a different action for each? In this chapter, we’ll learn how to write code that runs only when certain conditions are true.

3.1 Conditionals check values and adjust which code is run

We can ask Python to take different actions, depending on a condition, with an if statement:

num = 37
if num > 100:
    print('greater')
else:
    print('not greater')
not greater

The second line of this code uses the keyword if to tell Python that we want to make a choice. If the test that follows the if keyword is true, the body of the if (i.e., the lines indented underneath it) are executed. If the test is false, the body of the else is executed instead. Only one or the other is ever executed:

The diagram below shows how this choice is being made.

3.2 Indentation in Python is Pretty Important

The layout of code in Python is actually pretty important. The whitespace is structural and the amount of it tells us something about where we are in a program. Whitespace is particularly important in if . By convention the indent under each new if or else should be four spaces.

if x > y:
    do_something()

An if within an if needs further indentation - it must also be four spaces further in, so a total of eight spaces.

if x > 100:
    print("bigger than 100")
    if x  < 120:
        print("but smaller than 120")
    else:
        print("and bigger than 120")
else:
    print("x is too small")

This rule propagates, so a third level would need twelve spaces etc.

Note how the code above is structured now. Code at the same indentation is in the same group of code - at the same level. We can easily see which if and else go together as pairs. This is the point of using whitespace like this - it gives us clean and visually consistent programs which the designers of Python value.

A common gotcha is that you always have to undo the indent at the end of the block. The first bit of the rest of the code must always be fully at the left of the page or Python will interpret the code incorrectly.

These indentation rules apply in other places in Python code and we’ll come across them in due course.

Tip!
You are probably thinking that this is a bit of pain. Having to type in so many spaces is a bit tedious. For this reason, most text editors will allow you to use the `tab` key to enter four spaces instead of a genuine `tab`. They'll also show the spaces indented as little dots. Try playing about with the preferences in your text editor if you can't see this.

3.3 More ifs

Conditional statements don’t have to include an else. If there isn’t one, Python simply does nothing if the test is false:

num = 53
print('before conditional...')
if num > 100:
    print(num,' is greater than 100')
print('...after conditional')
before conditional...
...after conditional

We can also chain several tests together using elif, which is short for “else if”. The following Python code uses elif to print the sign of a number.

num = -3

if num > 0:
    print(num, 'is positive')
elif num == 0:
    print(num, 'is zero')
else:
    print(num, 'is negative')
-3 is negative

Note that the if and elif bits are mutually exclusive. Only one of them ever gets executed.

3.3.1 Testing equality

Note that to test for equality we use a double equals sign == rather than a single equals sign = which is already used to assign values.

3.4 Logical operators in tests

Python has all the standard logical operators that let us combine tests. Most commonly there is and and or. An and operator is only true if both parts are true:

if (1 > 0) and (-1 > 0):
    print('both parts are true')
else:
    print('at least one part is false')
at least one part is false

while or is true if at least one part is true:

if (1 < 0) or (-1 < 0):
    print('at least one test is true')
at least one test is true

3.4.1 What is True and what is False

True and False are special words in Python called booleans, which represent truth values. A statement such as 1 < 0 returns the value False, while -1 < 0 returns the value True.

True and False booleans are not the only values in Python that are true and false. In fact, any value can be used in an if or elif.

if '':
    print('empty string is true')
if 'word':
    print('word is true')
if []:
    print('empty list is true')
if [1, 2, 3]:
    print('non-empty list is true')
if 0:
     print('zero is true')
if 1:
    print('one is true')
word is true
non-empty list is true
one is true

It may seem strange to set things up this way, but in Python in practice it allows for some nice and easy to read and write constructions.

3.5 That’s not not what I meant

Sometimes it is useful to check whether some condition is not true. The Boolean operator not can do this explicitly.

if not '':
    print('empty string is not true')
if not 'word':
    print('word is not true')
if not not True:
    print('not not True is true')
empty string is not true
not not True is true

3.6 Quiz

  1. Consider this code:
if 4 > 5:
    print('A')
elif 4 == 5:
    print('B')
elif 4 < 5:
    print('C')

Which of the following would be printed if you were to run this code? Why did you pick this answer?

  • A
  • B
  • C
  • B and C
  1. Consider this code:
if 4 > 5:
    print('A')
if 4 <= 5:
    print('B')
if 4 < 5:
    print('C')

Which of the following would be printed if you were to run this code? Why did you pick this answer?

  • A
  • B
  • C
  • B and C
  1. Consider this code:
if 4 > 5:
    print('A')
elif 4 <= 5:
    print('B')
elif 4 < 5:
    print('C')

Which of the following would be printed if you were to run this code? Why did you pick this answer?

  • A
  • B
  • C
  • B and C