Range, Break, and Continue
In this lesson, you’ll see how execution of a for
loop can be interrupted using the break
and continue
statements. break
terminates the loop completely and continue
only terminates the current iteration.
break
example:
>>> for i in ['foo', 'bar', 'baz', 'qux']:
... if 'b' in i:
... break
... print(i)
...
foo
continue
usage example:
>>> for i in ['foo', 'bar', 'baz', 'qux']:
... if 'b' in i:
... continue
... print(i)
...
foo
qux
Congratulations, you made it to the end of the course! What’s your #1 takeaway or favorite thing you learned? How are you going to put your newfound skills to use? Leave a comment in the discussion section and let us know.
00:00
Now let’s take a look at iterating over a range of numbers. As you’ve probably imagined by now, you could create a list of numbers, and then for i in a:
we’ll make it print i
, and that will print those values out.
00:22
You can see 0
, 1
, 2
, 3
, 4
. And that’s all right for when you’re creating a small list, but what about if you want to do tens or hundreds or even thousands of numbers?
00:32
Well, fortunately, Python has a built-in range()
function which allows us to give a sequence of integers out. So we can replace this… with just that. If you just have a single value in there, range()
will start from 0
and then go up to—but not including—the value that you give.
00:52 That will be a direct replacement for what we’ve just seen. I’ll run it there. You can see we get the same there. Clearly, this now makes it nice and easy to generate large numbers without having to spend half an afternoon typing out a list of numbers.
01:10
You get it very quickly, it goes all the way up to 999
. But there’s more to it than that. If you give it two numbers, the first one is the start
number and the second one is the stop
.
01:23
So here we will go from 10
to 19
—because, again, 20
isn’t included. And if we want to change the increment, we have the thing called stride, or step
—certainly step
makes more sense to me.
01:46
So let’s do it in 2
. And now that will only do the even numbers. And you see again, because of the way the numbers work out, when you get up to 18
, because 20
isn’t included, if we’d put 21
, we’d get that there. So you can see, we go all the way up to 20
there.
02:10 And it doesn’t matter that this doesn’t fit into that pattern. It’s sensible enough not to get upset by that.
02:19
The final area we’re going to look at is altering the for
loop behavior. So, it’s possible to use a break
or a continue
statement within a loop and alter the way that the loop is executed. Let’s take a look at that. So once again, we’ll set up our list of words.
02:47 So there we have it. It’s just going to print those four values out. I’m sure you’re confident in that by now.
02:56
Let’s modify the way that that works. So firstly, let’s look at the break
. If we put a condition here, if there’s a 'b'
in i
, let’s break.
03:10
So, when we get to our second value, this will be True
and break
will happen and it won’t be executed. We see we just get foo
that time, because the second time around, there’s a 'b'
present in there.
03:27
If we change this from break
to continue
, what happens is just that time around the loop is aborted, and we go back to here with the next value.
03:38
You can see that the 'bar'
and 'baz'
ones will not get printed, but 'foo'
and 'qux'
will.
03:48
And there you go. So if you need to alter the way that a loop works, maybe not execute the command depending on what’s happening, then you have control over that completely. Now, another thing is that for
loops have else
clauses.
04:06 Here, we will see if the loop gets executed normally,
04:15
we get the contents of the loop, but we also get Done
at the end because we finished the execution normally. Now, if that doesn’t happen, the else
doesn’t get executed.
04:28
We can say if 'b' in i:
—just like before—break
. And this time, not only does the loop get broken, but that else
clause there doesn’t get executed.
marktompkins on Dec. 25, 2019
very interesting!
kbutler52 on Dec. 27, 2019
Thank you so much for breaking this topic down for me! Love how you helped me to understand it!!!!!
DanielHao5 on Jan. 22, 2020
It’s a good intro to this important topic. However, it should be expanded to show some good and practical examples - eg. deep-dive on some edge cases and show how-to approach on those questions.
Abdullah Dev on Feb. 28, 2020
Great work !! easy to understand and follow.
emalfiza on March 10, 2020
Your explanation is so amazing. just wow Darren
markthiele on March 17, 2020
Thanks, very nice!
paritalagt on April 5, 2020
its good explanation ,but you should include some advanced concept with for loop
jasonwilliams78 on May 1, 2020
Yes this is a great intro, but I could sure use more depth to the for loop using compounding logic on an intermediate level
Ghani on Oct. 15, 2020
Very good tutorial Darren; thank you so much!
Deepak Nallajerla on Dec. 18, 2020
When I started this video course I am thinking “I already know about for loops do I need to watch this video” on other side I was telling to myself Real Python will try to include something new. I am right, I didn’t know about “else” part in for loops. I learned one new thing today.
DoubleA on Feb. 10, 2021
@Darren,
Thank you for this brief tutorial. Is there a way to use the range()
function with floats in the context of for-loops? I’ve checked the official documentation and it says that all the parameters passed to this function must be ints. But, I can imagine cases where iterating over a range of floats using a float value as a stride / step could be necessary, e.g.:
for i in range(10.5, 20.5, 0.5)
Is there a concise workaround for this approach?
Cheers.
Bartosz Zaczyński RP Team on Feb. 11, 2021
@DoubleA If you don’t mind using NumPy, you can take advantage of its arange()
function:
>>> np.arange(10.5, 20.5, 0.5)
array([10.5, 11. , 11.5, 12. , 12.5, 13. , 13.5, 14. , 14.5, 15. , 15.5,
16. , 16.5, 17. , 17.5, 18. , 18.5, 19. , 19.5, 20. ])
It also comes with the linspace()
function, which returns evenly spaced numbers. However, you’d have to convert your step into the number of intervals:
>>> import numpy as np
>>> np.linspace(10.5, 20, int((20.5-10.5)/0.5))
array([10.5, 11. , 11.5, 12. , 12.5, 13. , 13.5, 14. , 14.5, 15. , 15.5,
16. , 16.5, 17. , 17.5, 18. , 18.5, 19. , 19.5, 20. ])
To achieve the desired effect in pure Python, you can whip up a custom function:
>>> def frange(start, stop, step):
... while start < stop:
... yield start
... start += step
...
>>> list(frange(10.5, 20.5, 0.5))
[10.5, 11.0, 11.5, 12.0, 12.5, 13.0, 13.5, 14.0, 14.5, 15.0, 15.5, 16.0, 16.5, 1
7.0, 17.5, 18.0, 18.5, 19.0, 19.5, 20.0]
DoubleA on Feb. 11, 2021
@Bartosz, thank you:)
The custom function seems to make more sense to me at this stage. Actually, it is quite concise and clear. I wasn’t aware of the yield
keyword in the context of generator functions though. Thanks for the tip!
BTW, for those who want to explore more –> the official documentation contains some useful information concerning this topic too.
elleneia on Oct. 19, 2022
My #1 takeaway was the understanding of Break and Continue! Break STOPS the loop when a given condition is found, whereas Continue SKIPS OVER items that meet the given condition but otherwise continues the loop. Thank you!
Libis Bueno on Jan. 5, 2023
Dan, your style is perfect for teaching, not to say that the other authors are not good, because they are. However, I find myself learning more from your tutorials. Really Wish you could do a whole series from start to end on learning Python. Keep up the great work.
nnpdba on March 20, 2023
Darren,
what is the purpose of else in the for loops? If the ‘for’ is executing successfully why is it that ‘else’ is also executing?
Bartosz Zaczyński RP Team on March 21, 2023
@nnpdba The else
code block in a for-loop will run when the loop terminates normally:
>>> for i in range(10):
... print(i)
... else:
... print("We've looped through all numbers")
...
0
1
2
3
4
5
6
7
8
9
We've looped through all numbers
Otherwise, when you break out of the loop early, then the else
clause won’t run:
>>> for i in range(10):
... if i == 5:
... break # Break out of the loop early
... print(i)
... else:
... print("We've looped through all numbers")
...
0
1
2
3
4
rwelk on Feb. 13, 2024
Found that I don’t use range in variable line instead I used it in the statement. Thanks for this alternate scripting technique.
Become a Member to join the conversation.
nkemakolam on June 13, 2019
wow