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.

NoteSyntax

The syntax for an if statement is as follows

if condition:
    carry_out_some_operations
elif a_different_condition:
    carry_out_different_operations
else:
    carry_out_even_more_different_ones

Notice that the code within an if statement is indented relative to the if line.

Describe how the modulo operator % has been used to find if a value is odd or even.

Modulo returns the “remainder” from dividing two numbers. Odd numbers always have a remainder of 1 when they’re divided by 2, whereas even numbers have a remainder of 0.

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.

NoteTest Yourself

Read the following lines of code and think about what the result might be. Then run them and see if your ideas are correct.

5==5
5==5.1
5=='5'

The first line asks whether 5 is the same as 5, clearly this is correct and so True is returned.

The second line compares the int 5 to the float 5.1 - clearly these are not the same and so False is returned.

The last line compares the int 5 to the string '5' - these are completely different types and so again False is returned.

Warning

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.

NoteTest Yourself

Read the following lines of code and think about what the result might be. Then run them and see if your ideas are correct.

5!=5
5!=5.1
5!='5'

We’ve switched out == for != and so get the opposite answers to the above example.

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\) >=
NoteTest Yourself

Read the following lines of code and think about what the result might be. Then run them and see if your ideas are correct.

5 < 6
5 > 6
5 <= 'ten'
  1. True
  2. False
  3. An error - this type of logical operation makes no sense and so is not defined in Python.

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
Note

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.

Read the following lines of code and think about what the result might be. Then run them and see if your ideas are correct.

'r' in 'Iron'
'R' in 'Iron'

True - The lowercase letter r is in Iron False- The uppercase letter R is not in Iron.

much like with the equality and inequality operators, there exists an opposite to the in keyword - not in.

Read the following lines of code and think about what the result might be. Then run them and see if your ideas are correct.

'r' not in 'Iron'
'R' not in 'Iron'

False - The lowercase letter r is in Iron True- The uppercase letter R is not in Iron.

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 < 10
False

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 < 10
True

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.

NoteSyntax

When using and and or, remember that:

and evalutates to True when both expressions on either side are True.

or evalutates to True when either (or both) expressions on either side are True.

Tip

We can shorten

number > 4 and number < 10

even more with the following syntax

4 < number < 10

This 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”.

Using elif, modify the above example to also alert the user when the value is zero. Think carefully about where the elif should be located!


# Pick a value!
value = 10

if value % 2 == 1:
    print(f'{value:d} is odd')
elif value == 0:
    print('The value is 0 (which is even!)')
else:
    print(f'{value:d} is even')

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.