Let's quickly talk about loops.
Loops are a way to go through every item in a sequence.
Now we know all about sequence types such as strings, lists,
tuples, and sets.
These, along with dictionaries, can actually be looped through.
And we've actually seen examples of that throughout previous videos already.
Now, when it comes to loops, in Python there are really two main loop types.
You have a for loop and a while loop, and they are drastically
different, but they do achieve the same thing.
So a for loop is a loop that will loop through every item
in a sequence until it's done, and then when it's done, it
just automatically stops; whereas a while loop will run until
you explicitly tell it to stop, and it will not automatically
stop until it meets some sort of criteria.
So as an example here, let's just create a simple loop.
So let's loop through every letter in a word.
So 'word = "Computer".
Then we can do 'for letter in word: print(letter)', and this
will just print out "C-o-m-p-u-t-e-r", computer, one letter at a time,
because this is a sequence.
This allows us to to loop through it one character at a time.
This works with lists, too.
So if we wanted to, we could cast this as a list.
We haven't formally learned about casting yet, but this is
going to basically turn this into a proper list.
So let's go ahead and cast this as a list, and I'm going to
insert a cell just below it.
And let's do 'type(
word)', is now a list.
I'm going to insert a cell
here. Let's see what 'word' is.
It is a proper list.
And let's rerun this.
We're going to see the exact same results.
Now, that is a basic for loop.
All it did was loop through each 'letter', and when it was
done it just stopped on its own.
A while loop, on the other hand, will not. A while loop basically
says, while something is true, do something, and it will go
on forever until you tell it to stop.
So be careful with this one, because this one can be a little bit
dangerous on your computer.
So what we're going to say here is, 'num = 1',
and 'while num <= 100:
[no audio]
print(num)'. Now, because this number is set to 1, and it is not
changing at all, ever,
this will run forever.
So what we need to do in here is build some sort of fail
safe. We want this number to eventually reach the number
100. So we say 'num = num + 1',
And after every iteration, this will add 1.
So this will go 1-2-3-4...97-98-99-100. And let's run this.
And here we can see it's going to go all the way down to 100.
In the next two lessons, we are going to learn more about
for loops, and we're going to learn more about while loops,
and looping through things like dictionaries as well.
So this was just a quick little overview.
You don't have to know exactly what I was talking about, about
anything in this lesson.
Really, this was just sort of a little bit of an introduction into
for loops and while loops.
We'll dive into those in their own videos.
They deserve their own videos.