Hello and welcome to Chapter 5, loops and iteration.
As always, this lecture is copyright Creative Commons Attribution, including
the audio and video and, and the slides, and the book even.
So, now we're getting to our fourth basic pattern.
We've talked about sequential, where steps happen one after another.
We've talked about conditional, where steps may or may not happen.
In Chapter Four we talked about the store and retrieve pattern.
And now we're going to talk about the looping pattern.
And the looping pattern is the last of our really foundational ones, and
it potentially is the most important one, because it's the thing that allows us
to get computers to do lots of things that, say,
humans might get tired of, but computers don't tire of.
And so after this we'll start sort of becoming a little more
skilled in the basic language capabilities.
We'll talk about strings and, and then start to talk about files.
Add start doing some real work after we get done with this, so bear with us.
It's going to be a while, but we'll get there.
We'll get there. So, welcome to repeated steps.
This is the example that I had in the first, first lecture, Chapter 1.
And the basic idea, just to review,
is that you have this while keyword.
The while keyword sort of functions like an if in that
it implicitly has a decision that it's going to make.
And it's either going to do the code in the
indented block or not do it, or skip it basically.
Alright? So you either do it or you skip it.
The difference between the while and the if is that it's going
to do it many times, as long as this question that we have remains true.
Okay?
And so, in this case, n is 5, while n greater than 0 functions like an if.
So yes, it's going to run it. Prints out 5, subtracts 1, so it's 4.
Goes back up.
Goes back up and asks the question again, is n still greater than 0?
Well, since it's 4, yes, we'll continue on.
Out comes 4 then n gets subtracted. 3, 2, 3, 2, and then
we come through, we print 1. Print 1.
We subtract n to 0. We go up, we go back up.
n is now not greater than 0, so we come
up and we execute outside the loop, we leave the loop.
And that really means in the Python code we
skip to whatever is lined with the while statement.
The same indent level as the while statement.
And so that's how it works, and
I just print n at the end here to remind ourselves that n ended up at 0, not at 1,
the last thing we printed out in the loop. The last thing we
printed out in the loop was the 1, but n ended up at 0 because
it was, this loop was going to run as long as n was greater than 0,
so n had to sort of be not greater than 0 to get out of the loop.
Okay?
So that's basically a review of what we've done.
Now, oh, wait, wait, wait, wait,
wait, something else. Iteration variables.
Okay, so the key to this is these loops can't run forever.
We don't want them to run forever.
We want them to run until, as long as we want them to run.
They may run a very long time, but not forever.
There's got to be a way to get out of them, otherwise we
call them infinite loops, which we'll talk about in the next slide.
And so the iteration variable is generally some variable
that is changing each
time through the loop, and we're changing it by subtracting 1 to it, from it.
And so this thing is going to keep running, and we
can pretty much see that Oh, this is going to exit, right?
Whatever n is, it could be a large number, but eventually it's going to get to 0.
Right?
So the iteration variable controls how many times the loop runs.
And it also allows us to do something different inside the loop.
And, of course, this is like a trivial
loop, where we're just printing the iteration variable.
But it just means that this loop is going to run
five times and it's going to do something potentially different each time.
If you just ran the loop that did the same thing over
and over and over again, with no data changing, that's kind of dull and pointless.
So just because you have an iteration variable
doesn't mean that you've properly constructed your loop.
It's a, it's a common problem or something we want to avoid,
is an infinite loop. And here is a, a carefully constructed loop.
We start n at 5 at the beginning.
We have a good question at the end, while n greater than 0.
It's going to run this
as long as n is greater than 0.
But the problem is, is we don't change in the little block.
We don't change the n.
Which means it's going to come back and n is going to be 5.
And it's going to run this and n is going to be 5.
And so this is an infinite loop, which means this loop will never exit.
It will never get out,
it's just going to run forever in here, because n is not changing.
Neither of these statements change n.
So part of the iteration variable is there needs to be something that changes
so that the loop will ultimately make progress to
accomplish what it is and know when to stop.
So this is an infinite loop and, of course,
Lather, Rinse, Repeat is commonly put on shampoo and conditioner.
And so you know, you can, next time you are
in the shower, take a look at your shampoo and
conditioner and find the infinite loop that's,
that's on most bottles of shampoo and conditioner.
Now here is another loop,
just to emphasize that it's possible to structure
these loops in a way that they never run.
So this function is, is an if.
The while functions as an if.
And so when n is set to 0 and we ask the question,
it is literally going to make the decision based on n greater than 0.
Well it is not greater than 0, so it's going to go right by it, over
here it's going to come in here and go right to there and never run these
lines of code. And that's, we call this a zero trip loop.
And that's okay. I mean, this is a silly one, of course.
It just shows that the test, the question that's being asked is
above the lines that make up the body of the loop.
And if it's false, the loop never runs.
So it's possible that these loops have zero trips.
Okay?
So, that's a loop.
Now, there are more than one way to sort of control the flow
of a loop.
The basic flow of the loop is when it gets to the
bottom, it goes back up to the while, and does the check.
This is a different way of getting out of
a loop or controlling the execution of a loop.
There is a keyword or a part of the Python language called...
What color do I got?
No, green's over here. Called break.
If you look back at the reserved words, break was one of the reserved words.
Break says,
hey, if I'm in a loop, stop the loop. All right?
Get out of this loop.
I'm done with this loop.
And so here's this loop.
Now the interesting thing we've done is I've
just got done talking to you about infinite loops.
We have just constructed an "infinite loop", because the
question is right there, and the answer is yes.
True.
And that's a way to construct an infinite loop.
We've done this because we have a different
way of getting out of the loop, so we've
constructed a loop that, just on the face of it,
just looking at that line, looks like an infinite loop.
So what this loop does is it reads a line of input,
checks to see if the string that we've entered is done.
And if it is, we're going to skip out with this break
and get out of the loop, otherwise we're going to print it.
So at a high level, what this loop is
going to do is prompt for strings of characters
until we enter done.
And that's exactly what it does.
It prompts, we say hello there, it prints that out.
We say, we say finished, it prints that out.
We say done, and it's done.
So it, when we say done, it comes out and
finishes the loop, and, and that's the end of the program.
Okay?
So, to look at this in some more detail.
The first time, it comes in, does the raw input.
Because True is true, so it's going to run it.
And then we enter hello there.
It checks to see if what we entered is equal to the string done.
It is not, so it skips and it does the print.
And we do this one more time, we type finished.
And then the line is not done, that variable
line does not have the value done in it.
So we print that. We come in
one more time, but this time this is true, so it
goes in and executes the break and then it escapes the loop.
And so you can think of...
Right?
Here is the body of this loop,
because that's where the indentation starts and ends.
The break says, break me out of the current loop that I am in
and get to that next line that has the same indent as the while.
So, whatever it is, break says, we are done with this loop.
When that statement executes, we are done with the loop.
We're finished with the loop.
It'll run until that executes because we got this set to be while True.
Okay, so there's a simpler, I mean this is sort of a simple way to draw this.
Break is sort of a jump to the statement immediately following the loop.
If you really want to picture this, I think
of this as a kind of like a Star Trek transporter.
Where you kind of come into break and then [SOUND] your molecules are sent
to the four corners of the universe, and you reassemble outside of the loop.
And so if we look at this in sort of my little road map
version of these things, right?
The while loop is going to run for a while, yada, yada.
There can actually be more than one break
as long as they only get this. But the moment that somehow, some if or
whatever hits the break, then it gets out completely and so it escapes the loop.
And so it sort of like you, you, you're zoom, zoom,
zoom, zoom, zoom, zoom, you come in here and then you are,
you are re-materialized outside the loop. That's what the break does, okay?
So, break is one way to control the execution of loops.
Now, another way to control the execution of
loops, that doesn't actually exit the loop, is called continue.
Continue basically says, hey, I'm done with this iteration of the loop.
Now each time through the loop, we call that an iteration.
Continue says, I don't want to stop the loop, but I
want to stop this iteration and advance to the next iteration.
And so what we have here is we have the same basic loop,
a while True which kind of makes us an infinite loop.
We're going to read a line prompting with a less than sign.
And if it's done, we are going to break, that code is
down here, and we are going to print it if we fall through.
So normally we'll be reading and
printing, and if the line is done, we are going to break out.
That's we just got done doing. But the new part is right here.
And this is, we'll learn this in the next chapter.
If line sub 0, if the first character of
the line, is a pound sign, we're going to continue.
And what continue says is it doesn't actually get us out of the loop.
It jumps back up to the top of the loop.
Which means that it ignores, for that iteration,
the rest of the loop. Right?
So if execution comes in here.
I'm going to clear that.
If execution comes in here and hits this line, it goes back up to the while.
Okay?
Which means it, whatever this is, it's not coming out of this if.
It's going back up to the while.
Okay?
So continue ends the current iteration and jumps to
the top of the loop, and starts the next iteration.
And so if we look at how the code runs,
hello there prints, pound sign with the first character
doesn't print, so there is no printout right here.
Print this is not done. And we enter done, and then the loop ends.
Now another way to sort of draw this is
the continued jumps to the top of the loop.
It, it does run the question, right? It does check the question.
So here is another way to, to draw
that picture. And so here again we have a loop and it's happily running.
And there can be breaks in there and there could
be continues in there, and as long as we don't
hit a break or continue, the loop just sort of
runs and goes up to the top. And at some point, some if,
we hit the continue. And like a transporter, instead of
going out of the loop, we go to the top of the loop.
But it's important that we go and we check the question, right?
So the continue is
not likely to exit the loop unless the question has become false.
So the continue is likely to come up here,
run some more, then hit the continue. It comes up here.
Oops! Oops, it did that backwards.
Run some more.
Clear this out.
So, the continue could run many times, right?
So we have the loop.
Loop runs a bunch of times, then finally we hit the continue.
Continue goes up to the top.
If it's still true, we'll run the loop some more.
Then you might hit the continue.
Then you might go up to the top, come
down, round and round and round and round, hit the continue again.
Go up to the top, yada, yada.
Now in this, in this particular loop, this break eventually
is down here and that's how we get out, okay?
So the continue goes back up to the top of the loop.
So these loops that we construct with the
while keyword are what we call indefinite loops.
I mean, looking at the ones that we've
written, which are two lines or six lines,
we can kind of inspect them and understand when they are going
to stop, and we are going to know that they're possible to stop them.
A loop that won't stop is an infinite loop.
Sometimes these loops can be rather [COUGH] complex and you may not actually be able to
look at them, because there are many lines and, and so we don't know.
And so, so if you, you have to be real careful when you
construct these to make sure that they stop as, as things get more complicated.
Now the cousin to indefinite loops are definite loops.
And definite loops is something where we have a list of things or a set
of things that are kind of a known set of things, a finite set of things.
And we are going to write a loop that's going to go through that set of things
and do something to each thing in that set of things.
And the keyword that we use for this is the for.
So we use the Python for keyword that says we are going to write a loop, but
instead of it just running until some condition
becomes true or false or we hit a break,
we're actually going to know how many times this is going to run.
Now you can actually use break and continue in for loops.
We call these definite loops because the, how long
they're going to run is kind of well known, basically.
So here's a simple definite loop, and it's kind of like that while loop
that we just got done looking at
where it's counting down and then saying blastoff.
And so the way we construct this loop is we have the for keyword,
it's part of Python language,
the in keyword, and then we have an iteration variable.
I've chosen i as my iteration variable.
And basically what we're saying is, dear Python,
run this indented block, and there's only one line in the indented block.
Run it once for each of the values in this little list.
This is a Python list, square brackets make Python lists.
Comma-separated values.
So it says, I would like i to be 5, then run this code.
Then I would like i to be 4, then run this code.
Then I would like i to be 3, then run this code.
i should be 2, then run this code. And i should be 1, then run this code.
And so this is pretty clear, and I like this word in.
It says you know, doop, doop, doop, doop, doop, and then run this each time.
And so out of that comes 5, 4, 3, 2, 1, and then the loop is done.
Python is doing all the tricky bits
here, Python's figuring all these things out for us
and handling all this, and then we're done. And so it's, it's, if you look at it,
we have an iteration variable, but we didn't have to increment it,
we didn't have to do anything. Python took care of a lot of things for us.
And so when we're looping through a known list of things,
or later when we read a file,
we're going to loop through the lines in the file.
And so the for loop is a really nice powerful.
And it's syntactically cleaner, it's really quite nice.
Now it's important to realize that you
don't have to just loop through numbers. I did that one with the set of
descending numbers, so that it was equivalent to the
while loop that I started at the beginning.
But this is a loop where what it's going to loop through is a list.
Closed square brackets are a list in Python.
This is a list of three strings, Joseph, Glenn, and Sally.
They're string constants, and then commas are how we make lists.
And so friends
is a mnemonic variable.
Python doesn't know anything about friends in particular,
but I've chosen this variable name to be friends.
And it's a list of three people, Joseph, Glenn, and Sally.
And so I have an iteration variable called friend.
And I'm going to loop through the set of friends.
Now Python doesn't know anything about singular.
Python doesn't know anything about plural.
I'm just choosing these variable names because it makes a lot of sense.
This is a set of friends. Because it has three of them in it.
And this is a single friend.
What it's really going to do is friend is going to take on the successive
of values Joseph, Glenn, and Sally, and this little block of code
is going to once for each of those three items in the set, and
the variable friend is going to take on the successive values of that set.
So out of this comes three lines of printout.
Happy New Year Joseph, Happy New Year Glenn, Happy New Year Sally.
Of course this is the i bit right down here, but we just
made it so, hey Python, look, how ever many friends they are, run this
code one time for each one, change this variable friend to be each
of the successive ones in order, and then we print that we're done.
Okay?
So the for loop.
Sort of if we go and try to make a picture of the for loop.
The for loop is kind of a powerful thing. It's does, it does two things.
It decides if we're done or not.
Do we keep going in the loop?
Or, well I mean as long as we keep
going, we're going to advance the i value, the iteration variable.
It takes care of the responsibility of changing the iteration variable.
We do not have to add lines of code in that change the iteration variable, okay?
And so if we take a look, you know, we come in.
Are we done? We're not done.
Set i to the right thing, then print it.
Out comes 5. Advance i,
advance i, print it. Advance it.
Print it. Advance it. Print it.
Oh, now we're done.
Right?
i was not the thing that decided when we were done.
The for loop just keeps track internally as i moves
through these things and it goes like oh, I'm all done.
I'll take care of that, you finished.
So it doesn't, there's no if in here, so it's not like like if i equals 1, stop.
No, no, no, it just says you told me to do five things.
I'm going to do five things
and then we're going to stop.
And so again the for loop, the for loop here has got sort of two functions.
It decides how long the loop is going to run, and changes the
iteration variable based on what you've told it to, in this in clause.
Okay?
So I think in is a real elegant construct.
It's just a keyword, but it's sort of, if you think about math,
if you're familiar with sets,
it's like something inside of a set of something.
I think it's a real pretty way to think about it.
And you can kind of think of it a little more abstractly.
That you say, well here's a little indented block of code.
Right?
And I want it to run some number of times for each
of the i values in the set 5, 4, 3, 2, 1.
That's how I kind of think of it.
So I think that this is a real pretty syntax.
Different languages have different looping syntax.
I think this is really a very expressive, very pretty one.
Yeah.
So another way to, so, so, so one way to
think about this picture is that, you know, the for loop
causes sort of repeated execution in that we're
driving in the circle and then we stop, right?
The other way to think about is to, to
not, to think about a little more abstractly, right?
To say, hmm, you know, at the end of the day, all I'm
really telling Python is, I want to execute this block of code five times,
then I want the variable i to change from, to these three values.
So in a way, you could think of this as expanded
is the for loop sets it to 5, then runs your code.
The for loop then sets it to 4, runs your code.
The for loop sets it to 3, runs your code.
For loop sets it to 2, runs your code. Sets it to 1, runs your code.
These two ways of looking at it are the same
from your perspective, because you're just asking Python
to do something.
Whether it does it this way, or whether it does it this way,
you hardly can tell the difference. It's probably going to do it this way.
But logically it's not that different. It's not different from doing it this way.
You're saying, run this block of code, change i in the following way.
Cool. It's like, we don't have to worry.
I mean, we can use, mentally, either model of what's
going on inside, because it doesn't matter, because they're the same.
Okay, so these definite loops are really cool.
Starting in a couple of chapters we'll mostly use definite
loops to go through lists or dictionaries or tuples or files.
And so that's a finite set of things.
It can be a large set of things, but it's a finite set of things.