Logic
Now we know how to make Python repeat an action using a loop, but how can we get Python to switch between different actions depending on an input?
Consider the following example in which we take an integer and decide whether it’s odd or even.
# Pick a value!
value = 10
if value % 2 == 1:
print(f'{value:d} is odd')
else:
print(f'{value:d} is even')Here we’ve used an if statement to control the flow of the program, producing one result if the value is odd, and a different one if the value is even.
Logical operators
One thing has yet to be explained in the above example - the equality operator == which checks if two values are equal. This is a form of logical operator and returns either True if the values are the same, or False if they aren’t - remember that we encountered these boolean variables way back in Session 1, but didn’t have a use for them at that time.
The assignment operator = is totally different to the equality operator == - even if they look similar!
The opposite of the equality operator is the inequality operator which is written as !=. This asks “are these two values different?” and returns True if they are, and False if they aren’t.
There are quite a number of logical operators in Python - the subset that you’ll use in this course are collected in the following table.
| Condition | Mathematical Notation | Operator |
|---|---|---|
| Equals | \(=\) | == |
| Not equal to | \(\neq\) | != |
| Less than | \(<\) | < |
| Less than or equal to | \(\le\) | <= |
| Greater than | \(>\) | > |
| Greater than or equal to | \(\ge\) | >= |
in
In addition to the logical operators above, Python also allows us to test whether or not a given element can be found in a sequence.
'Fe' in ['Cr', 'Mn', 'Fe', 'Co', 'Ni']True
We’ve sort of implied it so far, but a sequence is a Python object which contains items in order - e.g. list, tuple, dict, and str.
much like with the equality and inequality operators, there exists an opposite to the in keyword - not in.
and & or
We now have the toolkit to evaluate basic logical statements
# Assign 'purple' to favourite_colour
favourite_colour = 'purple'
# Evaluate whether or not favourite_colour equals 'red'
favourite_colour == 'red'False
but its often neccessary to combine logical operators. For example, what if we want to know whether a number is greater than 4, but less than 10? We already know how to test these two conditions separately
number = 11
print(number > 4)
print(number < 10)True
False
We could combine these into a single line using the and keyword.
number > 4 and number < 10False
This gives us a single bool. The and keyword will only return True if both of the expressions on either side also evaluate to True. We have already seen that number < 10 is False, hence the whole statement evaluates to False.
Rather than and we can also combine logical expressions with the or keyword.
number > 4 or number < 10True
Using the same expressions as before, we now find that by replacing and with or, the whole statement evaluates to True. The or keyword evalutes to True if either expression on either side is True.
We can shorten
number > 4 and number < 10even more with the following syntax
4 < number < 10This is a lot closer to the mathematical notation you’re used to, e.g.
\[ 4 < x < 10 \]
Back to if
Now that you understand logical operators, and, or, and in, let’s revisit the example at the top of this page.
# Pick a value!
value = 10
if value % 2 == 1:
print(f'{value:d} is odd')
else:
print(f'{value:d} is even')Taking this line-by-line, we see that in the if statement, we first test if the value has a modulo of 1. This line is the same as
if (value % 2 == 1) == True:which is quite cumbersome, so we can just skip the == True and brackets. This has the side-effect of making the code more readable - in English this can be read out loud as
“If the modulo two of the value variable is equal to one, then print that the value is odd.”
The only difference is that Python, unlike some languages, doesnt bother using then as a keyword.
The second keyword in this example is else - you can probably guess that this means “otherwise do this”. In our case, we know that if a number isn’t odd it has to be even, so we don’t bother computing value % 2 == 0 since there’s no point, and just say “otherwise, print the value is even”.
If we want to include more if criteria, then we need to use elif after the initial if (see the Syntax block at the top of the page) which is short for “else if”.
Exercise
1. Imagine that you are playing “Rock, Paper, Scissors” with a friend - they have (unbeknownst to you) picked rock.
Write some Python to decide who wins depending upon your weapon of choice.
2a. Write a program that can tell whether or not a word has any vowels in it.
2b. Extend your program by checking if the word contains no vowels and does not contain the letter t.