Making Choices

Overview:

  • Teaching: 10 min
  • Exercises: 10 min

Questions

  • How can programs do different things based on values?

Objectives

  • Understand the structure of conditional statements
  • Understand the flow of if, elif and else branches
  • Correctly evaulate logical expressions containing and and/or or

In our last episode we looked at loops, one of the fundamental building blocks of programming, because they allow us repeat tasks many times. We now look at on of the other main building blocks, conditional statemnts, which allow us to make choices.

In Python we can make our programs take different actions, depending on conditions using an if statement:

In [1]:
num = 37
if num > 100:
    print(num, "is bigger than 100")
else: 
    print(num, "is smaller than 100")
print("Done")
37 is smaller than 100
Done

The following decision diagram helps to understand what is happening:

Decision Flow Diagram

We enter the section of code at the top and arrive at the diamond, where the program checks whether the value in variable num is greater than 100. If the condition is True the program takes the left branch, and if the condition is False it takes the right branch. Once the conditional is finished to two branches come back together.

The else branch can be omitted as in:

In [2]:
num = 163
if num > 100:
    print(num, "is bigger than 100")
print("Done")
163 is bigger than 100
Done

Or we can have additional elif branches:

In [3]:
num = 42
if num > 100:
    print(num, "is bigger than 100")
elif num == 42:
    print(num, "is the Answer to the Ultimate Question of Life, the Universe and Everything")    
else: 
    print(num, "is smaller than 100")
print("Done")
42 is the Answer to the Ultimate Question of Life, the Universe and Everything
Done

The structure of conditionals

Let's look at this in more detail:

  1. The structure of a conditional statement begins with an if statement.
  2. Then we have the condition which typically makes a comparison between two values, in our example, the value stored in num and the value 100
  3. The condition is that the first value should be greater, >, than the second value.
  4. If the condition is True we execute the body that follows.

An elif statement is essentially the same as an if statement except that it can only follow an if, or another elif. It has a separate condition and also causes the body following it to be executed if the condition is True. An else statement allows us to execute a further body of code if none of the preceeding conditions are True.

In Python, similar to what we saw in loops, the statements if, elif and else, must be followed by a colon ':' and the body of code following them must be indented.

True and 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.

Conditional Operators:

In Python we can use the following conditional operators:

Operator Operation
> Greater than
>= Greater than or equal to
== Equal to
<= Less than or equal to
< Less than

Note that the operator for is equal to is two equal signs ==.

Boolean Operators

We can combine conditional statements using the Boolean operators, and and or. If we use these it is useful to put the conditional components is parentheses (brackets) so that our intention is clear:

In [4]:
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
In [5]:
if (1 < 0) or (-1 < 0):
    print('at least one test is true')
at least one test is true

We can also use the not operator to invert the condition:

In [6]:
if not( (1 > 0) and (-1 < 0) ):
    print('not (both parts are true)')
else:
    print('false that not (both parts are true)')
false that not (both parts are true)

How many paths?

Consider this code:

if 4 > 4:
    print('A')
elif 4 == 4:
    print('B')
elif 4 <= 4:
    print('C')

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

  1. A
  2. B
  3. C
  4. B and C

Solution

Close Enough

Write some conditions that print True if the variable a is within 10% of the variable b and False otherwise. Compare your implementation with your neighbour’s: Do you get the same answer for different pairs of numbers?

Hint: Use the function abs(value) to obtain the absolute of a value.

Solution

Counting Vowels

  1. Write a loop that counts the number of vowels in a character string.
  2. Test it on a few individual words and full sentences.
  3. Once you are done, compare your solution to your neighbour’s. Did you make the same decisions about how to handle the letter ‘y’ (which some people think is a vowel, and some do not)?

Hint:

  • for ch in string: loops over each character in a string in turn;
  • if test_ch in string: is True if the value in test_ch is a character in the string

Solution

What Is Truth?

True and False booleans are not the only values in Python that can be evaluated 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')
if undeclared_variable:
    print('is true')

After reading and running the code above, explain what the rule is for which values are considered True and which are considered False.

Key Points:

  • Use if condition to start a conditional statement, elif condition to provide additional tests, and else to provide a default.
  • The bodies of the branches of conditional statements must be indented.
  • Use == to test for equality.
  • X and Y is only True if both X and Y are True.
  • X or Y is True if either X or Y, or both, are True.
  • 0, 'the empty string', and 'the empty list' are considered false; all other numbers, strings, and lists are considered true.
  • True and False represent truth values.