Breaking Out of the Pattern
00:00 Sometimes you get stuck in a loop, and all you need to do is to break out of it. In this lesson, you’ll be covering, bringing loops into the mix. So far, you’ve been looking at conditional statements and creating branches for your program, but how do loops fit into it? And why is that useful?
00:17
You’ll be using the break
keyword to completely stop a loop in its tracks. You’ll be looking at the continue
keyword to stop a current iteration of a loop but continue the actual loop.
00:30 Take a look at this example. What this example is trying to do is to take the sum of all even numbers between 0 and 100 and print that sum. So all even numbers between 0 and 100—for example, the first even number between 0 and 100 is 2.
00:48 Then it’ll be 4, 6, 8, and so on. So you’ll want to sum 2 with 4. 6. Then with 6, which will be 12. So on, so on. You’ll want to do this all the way up to 100.
01:00
So the way you can do this is define, first of all, a variable, sum_of_evens
, and set that equal to 0
. That will be the variable that you’ll increment every time you reach a even number.
01:12 Now you have to check each number in turn from 0 to 100. And check is the hint word here. This is where conditions will come in. But first we need to get each number to be able to check them.
01:22
So we can do this with a for
loop. for n in range(101):
So that’s taking the range()
function with the argument of 101
.
01:33
That’s giving you an iterator between 0
and 100
. So in each iteration of this for
loop, n
will be 0
, then 1
, then 2
, then 3
, then 4
, then 5
, all the way up to 100
.
01:44
And now we want to check whether this n
is even. The way we can do this is with the modulo operator (%
). The modulo operator divides the number on the left-hand side with the number on the right-hand side and will return the remainder of that division.
01:59
So to check if a number is even, you can divide it by 2
and check if there’s no remainder. So you can do n % 2
, and if the remainder is 0
, then you know it’s even. So putting that together in an if
statement, you do if n % 2 == 0:
then you can take the sum_of_evens
, set it equal to the sum_of_evens + n
.
02:23
So that’s taking its own value and adding on n
to it and assigning it to itself. That loop is going to run a hundred times, and once it’s done, you’re going to print the sum_of_evens
.
02:39 So that’s an example of where a conditional statement can come in very handy in a loop.
02:46
And as you can see this code here in IDLE, if you run this, you’ll get the answer of 2550
. That is the sum of all the even numbers between 0 and 100.
03:01
Now it’s time to take a look at the break
keyword. Take a look at this quick example, for n in range(4):
So that’s going to be iterating over 0
, 1
, 2
and 3
— 4
not included—and it’s doing a check. if n == 2:
then break
and it’s going to print n
.
03:21
So on the first iteration, you’ll have n == 0
, so if n == 2
is False
in that case, so then it’s going to go into print(n)
. It’s going to print 0
. For 1
, it’s going to be the same. Then for 2
, it’s going to go into this if
statement, and the question is, what does break
do here?
03:39
So go over to IDLE and run it to find out. So it’s printing 0
and 1
, but it’s not printing 2
. So by the time it gets to the break
statement, basically the for
loop is done.
03:51
break
means I want this for
loop to finish in its tracks and just move on to the next thing.
03:59
Take a look at this other example of a while
loop, because the break
keyword also works with while
loops. So we’ve got n
starting at 0
and we have a while True:
So if you’re not careful, while True
loops can run forever.
04:13
So you need to be careful to always use some kind of break
keyword in here to make sure that it doesn’t run forever. This can crash your computer, so be careful.
04:23
This will print n
, which is 0
on the first iteration, and then if n > 5
, it’s going to break. But if it doesn’t break, then it’s just going to carry on, and it’s going to increment n
by 1
by doing n = n + 1
.
04:37
Then it’s going to go back up to the top and print n
again. So it’s going to print 0
, 1
, 2
, 3
, 4
, 5
.
04:43
And then when n
is over 5
, which will be when n
is 6
, it’s going to break and exit out of that while
loop.
04:51
Pause the video and experiment with that in IDLE and see if you can get it working. Have your task manager handy in case the while
loop runs away with you.
05:00 If your computer seems to hang, then maybe you haven’t broken properly, or the condition you’ve made will never be reached, in which case you can just kill the Python process with your task manager and start again.
05:16
Now it’s time to start looking at the continue
keyword. Taking a look at this example, you’ve got a for
loop, very similar to the example with the break
keyword.
05:28
This will go through the numbers 0
to 3
. If n == 2
, then it will print "there goes two"
and continue.
05:37
And it will print n
in all cases. So what do you think is going to happen here?
05:44 Going over to the REPL to test this out,
05:50
you could see that print 0
, 1
, and then instead of printing 2
, it prints There goes two
, and then it prints 3
.
05:58
So what’s happening here is that it goes through 0
and 1
. The if
block is evaluating to False
, so the indented block corresponding to it doesn’t run, and it just prints n
. But when n == 2
, it will print "There goes two"
, and then when it hits the continue
keyword, it will say, okay, this iteration is done—not the whole for
loop, but only this loop of all the other loops to come in the for
loop.
06:24
So then it’s going to skip print(n)
, and n
will then become 3
. So then it will print 3
.
06:35
Here’s another example for you to play around with. Like the previous while
loop example, you’ve got n = 0
to start off with, and then you’re entering into what could potentially be an infinite while
loop, because the condition is just True
.
06:51
You need to make sure that you can eventually reach a break
keyword in there, and if not, have a task or process manager handy to be able to kill the process in case you mess up.
07:03
It prints n
, which will be 0
the first time, and then if n < 5
, which will be true the first time, it will increment n
by 1
, and then it will continue.
07:15
So that means it’s going to skip whatever is after it in the loop and go back to the top of the while
loop. So, n
is now 1
.
07:25
So it’s going to do that a bunch of times until n
is equal to 5
, because then if n < 5
will be False
.
07:36
In that case, it’s going to break, and then the loop is going to end. And you’ll note that this print()
statement at the end, after the if
… else
block, never gets printed, because this if
… else
block will always run one of its branches, and each of the branches has either a continue or a break statement, which means that no matter what, this print("end of loop")
statement will never get printed. Have a play around with that on the REPL.
08:05
In this lesson, you’ve covered bringing loops into the mix, combining loops with conditional statements and branching. You’ve been using the break
keyword to stop a loop dead in its tracks and continue on after the loop, as if the loop had already finished.
08:19
And you’ve been using the continue
keyword to stop an iteration of a loop and continue on to the next iteration of that loop.
IkedaMiqo on July 10, 2023
Copying the example, my code also printed each number from 0 to 6. Looking back on the notes from previous chapter, the > operator will evaluate an equal number as False, and thus keep going for one more step (as 5 is not greater than 6). To get the intended result of printing 0 through 5, my code ended up looking like this;
n = 0
while True:
print(n)
if n >= 5:
break
n = n + 1
By changing the boolean operator from > to >=, it will now break when the value is exactly 5 (or less). Hope that helped xD
Kyle E on April 30, 2024
Can you please explain the “while True:” part of the code? I don’t understand what True is referring to - it seems nothing in the rest of the while loop would produce a True value
Bartosz Zaczyński RP Team on April 30, 2024
@Kyle E It’s an idiomatic way to start an infinite loop, which you may let run in the background, for example, to serve network requests. The while
loop will continue running while the condition holds true. In this case, the condition always evaluates to true because you use the True
constant.
Kyle E on May 1, 2024
Thanks Bartosz!
Become a Member to join the conversation.
M B on May 27, 2023
in 4:43, he says it will print until 5. When I ran the While True loop, it evaluated until 6. Why is that?