Conditional Statements and Loops#
Learning Objectives:#
To have an understanding of and be able to use loops and conditional statements.
Have an appreciation of why we must make data visually accessible.
To know what features need to be present on a high quality plot.
Be able to create high quality plots using the Matplotlib.pyplot library.
To be able to plot a function.
To be able to plot multiple plots on the same canvas
Overview#
In this session you will be introduced to the concepts of conditional statements and loops. You will learn how to use if, and, else, elif statements and for and while loops. We are going to understand why we may wish to make graphical representations of data, have an awareness of the features that must be present on a high-quality plot, and then learn how to make high-quality 2D plots using Python.
Conditional Statements#
Often when we are coding we want the computer to make decisions for us. For example, when boiling a kettle, we would like the kettle to know when to stop supplying energy to the water. In this example, we would get the kettle to ask itself “is the water at boiling point?” - if the answer is yes then it should turn off, if the answer is no it should not turn off.
Single Conditions#
All of the conditions that we define are either True or False - these are boolean types. We can use if, else and elif (else if) statements to control tasks on the basis of if a condition is true or false.
The simplest example of checking conditions is comparing numbers.
# First, let's check if the following statements are true or false:
print(1==1)
print(1==2)
print(1<2)
# The notation for different conditional operators are as follow:
# "==" - is equal to
# "!=" - is not equal to
# "<" - is less than
# "<=" - is less than or equal to
# ">" - is greater than
# ">=" - is greater than or equal to
True
False
True
Once we are able to determine if conditions are true or false, we can get Python to perform tasks using conditional statements. For example, below is an example of how we may use if and else statements:
a = 6
b = 10
if a > b:
print("a is larger than b")
else:
print("a is smaller than b")
a is smaller than b
In the example above, Python checks if the first statement is true, if it is, the computer will print “a is larger than b”, but if it is false, it will print “a is smaller than b”. The example is great if a and b are different numbers, but there is no command for the computer to follow if they are the same number. We can use an elif statement to correct this:
a = 6
b = 10
if a > b:
print("a is larger than b")
elif a == b: #elif checks if a second condition is True
print("a and b are the same number")
else:
print("a is smaller than b")
a is smaller than b
Now Python will first check the first statement to determine if a is larger than b, if this is not true it will then go to check the second statement to determine if a and b are equal. If neither of these statements are true, the third statement must be and the computer will tell us that “a is smaller than b”.
Multiple Conditions#
It is often the case that we will want to get the computer to do things only if multiple conditions are true, or if one of many possible conditions are true. We do this all the time in real life, for example, I may get my phone to remind me to pay my credit card bill if:
the payment is due today and my balance is greater than £0
OR
it’s payday and my balance is greater than £0.
From the example above, the logic behind the decision as to whether to remind me to pay my credit card bill or not is clear. In either case, I will not receive a reminder if my balance is clear and I have nothing to pay, however if I have an outstanding balance I should be reminded to pay it if the payment is due (to avoid additional charges) or if it is payday (and I am settling my monthly finances).
In Python, we can apply the same logic using and and or statements:
a = 5
b = 2
c = 3
d = 7
# Using an "and" statement:
if a > b and c < d:
print("All of the conditions are True.")
else:
print("At least of the conditions is not True.")
All of the conditions are True.
# Using an "or" statement:
if a < b or c < d:
print("At least one of the conditions is true")
else:
print("Neither of the conditions are true")
At least one of the conditions is true
# We can combine "and" and "or" statements:
if (a == 5 and b == 2) or (c == 4 and d == 3):
print("At least one of the conditions is true")
else:
print("Neither of the conditions are true")
At least one of the conditions is true
Loops#
As mentioned in week 1, one of the main reasons we use computers is to get them to do all of the boring repetitive tasks we don’t want to do. When we are coding, we can tell the computer to iterate a task by using loops. There are two loops to be aware of: for loops and while loops.
While Loops#
A while loop allows us to iterate through a task until a condition is no longer met. In the example below, each time the loop runs it will print the value of count and add 1 to it. It will continue to do this until count = 15.
count = 0
while count < 15:
print(count)
count = count + 1
print('Task completed.')
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
Task completed.
This was a nice and simple loop, however sometimes the tasks we are doing may be more complex and we do not know what criteria will be required for the loop to end. In some instances the loop may run indefinitely. For this reason, we can add a break statement in the loop:
count = 0
while count >= 0:
print(count)
if count == 20:
print("The loop has been terminated")
break
count = count + 1
print('Task completed.')
0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
The loop has been terminated
Task completed.
For Loops#
The next loop we are going to take a look at is the for loop. The for loop again allows us to repeat a task as we iterate through a range of values or series of variables. For example, we can iterate through a list and print each item within in it:
items = ["Trying","to","catch","moonbeams","with","a", "butterfly", "net"]
for word in items:
print(word)
Trying
to
catch
moonbeams
with
a
butterfly
net
How about an example with a calculation?
numbers = [1,2,3,4,5]
for i in numbers:
value = i**2
print(value)
1
4
9
16
25
Perhaps we wish to use the index location in our loop..
for i in numbers:
print(items[i])
to
catch
moonbeams
with
a
Often we will want a task to be repeated a set number of times. We can use the range and enumerate commands to do this.
# This loop will simply print the value of i, which has been set to a range of 10 values (starting at 0)
for i in range(10):
print(i)
print(" ")
# Alternatively, we can give range() a start and stop point and tell it the increments to increase in.
for i in range(1,20, 2):
print(i)
0
1
2
3
4
5
6
7
8
9
1
3
5
7
9
11
13
15
17
19
What if we want the best of both worlds, i.e. we want to move through a list but also know how many times the loop has run? There are two ways we could do this:
items = ["Trying","to","catch","moonbeams","with","a", "butterfly", "net"]
counter = 0
for word in items:
print('The number of times the loop has run is', counter, 'and the word is: ', word)
counter = counter + 1
print(" ")
# There is nothing wrong with this method, but we can use the enumerate command to simplify our code:
items = ["Trying","to","catch","moonbeams","with","a", "butterfly", "net"]
for counter, word in enumerate(items):
print('The number of times the loop has run is', counter, 'and the word is: ', word )
The number of times the loop has run is 0 and the word is: Trying
The number of times the loop has run is 1 and the word is: to
The number of times the loop has run is 2 and the word is: catch
The number of times the loop has run is 3 and the word is: moonbeams
The number of times the loop has run is 4 and the word is: with
The number of times the loop has run is 5 and the word is: a
The number of times the loop has run is 6 and the word is: butterfly
The number of times the loop has run is 7 and the word is: net
The number of times the loop has run is 0 and the word is: Trying
The number of times the loop has run is 1 and the word is: to
The number of times the loop has run is 2 and the word is: catch
The number of times the loop has run is 3 and the word is: moonbeams
The number of times the loop has run is 4 and the word is: with
The number of times the loop has run is 5 and the word is: a
The number of times the loop has run is 6 and the word is: butterfly
The number of times the loop has run is 7 and the word is: net
Nested Loops#
One final thing to consider before we move on is to consider what we could do if we were to embed a loop into another loop. This is known as a nested loop and although their use case may not be immediately obvious, they are a very powerful tool to have at hand!
# An example of a nested loop. This nested loop will print out the times tables up to 10 times 10!
for i in range(1,11, 1):
print("The first ten multiples of ", i, " are: \n")
for a in range (1,11,1):
value = a * i
print(value)
print("\n")
The first ten multiples of 1 are:
1
2
3
4
5
6
7
8
9
10
The first ten multiples of 2 are:
2
4
6
8
10
12
14
16
18
20
The first ten multiples of 3 are:
3
6
9
12
15
18
21
24
27
30
The first ten multiples of 4 are:
4
8
12
16
20
24
28
32
36
40
The first ten multiples of 5 are:
5
10
15
20
25
30
35
40
45
50
The first ten multiples of 6 are:
6
12
18
24
30
36
42
48
54
60
The first ten multiples of 7 are:
7
14
21
28
35
42
49
56
63
70
The first ten multiples of 8 are:
8
16
24
32
40
48
56
64
72
80
The first ten multiples of 9 are:
9
18
27
36
45
54
63
72
81
90
The first ten multiples of 10 are:
10
20
30
40
50
60
70
80
90
100
Think about what the snippet of code above is actually doing. You may find it useful to work through the loop and write down what it is doing to understand how it works.
Activities#
Below are some exercises to complete to practise using conditional statements and loops. You may wish to review the notes from previous weeks to help you complete these exercises.
For the given list of numbers, write a loop that identifies the smallest and largest numbers in the list. The loop should print both of these numbers. You may find it useful to use the min() and max() functions for this task.
import numpy as np
# Complete exercise 1 here.
theData = [22, 2, 6, 3, 8, 9, 3, 8, 7, 9, 20, 40]
For the given list of names, write a loop that determines if the name “Issac” is present. The loop should print a statement indicating if the name “Issac” is or is not present in the list.
nameList = ['Daisy', 'Rosie', 'Florence', 'Sophia', 'Lily', 'Emily', 'Issac', 'Ella', 'Poppy', 'Amelia ']
Define two numbers as floating point numbers, write a function that tells you which of the two numbers is the largest and which of the product and sum of the two numbers is the largest. Test this for multiple number pairs.
This one is up to you! Create a while loop that outputs something until a condition of your choosing is met.