Combining loops and logic#
All of our examples so far have been relatively simple individual logical statements, but there is no reason that we cannot apply logical operations in loops:
for number in range(1, 22):
if number % 3 == 0:
print(f'{number} is divisible by 3.')
3 is divisible by 3.
6 is divisible by 3.
9 is divisible by 3.
12 is divisible by 3.
15 is divisible by 3.
18 is divisible by 3.
21 is divisible by 3.
Here we have combined a simple if
statement with a for
loop to find all of the multiples of \(3\) between \(1\) and \(21\).
In addition to all the logic we have learnt about thus far, there are two useful keywords that are relevant specifically to using logic in loops.
for number in range(1, 101):
if number > 10:
break
print(number)
print('We have broken out of the loop!')
1
2
3
4
5
6
7
8
9
10
We have broken out of the loop!
In the example above, we are looping over numbers between \(1\) and \(100\). The if
statement checks if number
is greater than \(10\), and if it is, the break
keyword is run. As the name implies, the break
keyword breaks us out of the loop: it stop the rest of the iterations that would otherwise have run from occurring. You can see this happening above because as soon as 10
is printed, no more numbers are displayed and instead the 'We have broken out of the loop!'
message is seen, which should only be printed after the loop has finished.
The other keyword that pairs nicely with the logic we have learnt is continue
:
for number in range(1, 101):
if number % 5 != 0:
continue
print(number)
5
10
15
20
25
30
35
40
45
50
55
60
65
70
75
80
85
90
95
100
Here we are testing whether or not number
is not divisible by 5
. If number
is divisible by 5
, then the continue
keyword does not run and we print
the number
. If the number
is not divisible by 5
, then the continue
keyword is run and this immediately skips us to the next iteration of the loop. The end result is that print(number)
only runs if number
is a multiple of 5
.
So, to summarise:
break
- When this runs, we exit the loop immediately.
continue
- When this runs, we skip the rest of the code in the loop and immediately skip to its next iteration.