Welcome back.
In this video we're going to learn about the for loops.
A for loop is used for iterating over a sequence that is either a list, a tuple, a dictionary, a
set, or a string.
Use for loops to repeat an action for each item in the sequence.
For example, if we need to print numbers from 1 to 5, five is included.
We use something called range and the for loop.
For I.
The index in range 1 to 6 six is not included.
Range includes one and two, three, four, and five.
For every time go increase I by one and print number I.
So here we are having the formatted string.
We are placing I with its value in each iteration and each iteration it increases I by one.
Let me run the cell and here we go.
Number one, number 2345.
And here is the output.
So this is the for loop in Python.
For I in range 1 to 6, go and print this statement.
Another loop.
Using a list of names we have names list Alice, Bob, Charlie for name for each name in names.
This is the meaning for each name in names.
Go and print hello message and place the name of the current iteration.
Run this cell and here we go.
Hello, Alice.
Hello, Bob.
Hello, Charlie.
Also, we can use the for loop with strings.
So for x in Alice print X, run the cell and here we go a l I c.
Every character inside this string will be printed in a new line.
So here we can iterate over strings.
Even strings are iterable objects.
They contain a sequence of characters.
Okay, so this is the usage of the for loop.
There is something interesting in for loops, we can break the loop and the iterations if we satisfy
a condition.
For example, if I want to stop this, iterate this loop and iterations on Bob, what we need to do
we can use here.
If name equals to Bob, then go and break with break statement.
We can stop the loop before it has looped through all the items.
Let me run and you can see we are not.
We are not executing all the iterations.
Alice, Bob, Charlie.
When the loop gets into Bob and reaches Bob, it break and stops the iteration.
Okay, so this is the power of using break, and we can use it in certain conditions if they are satisfied
in many ways and in many examples.
Okay.
So this is a very important thing in order to control and stop the loop if you reach a specific condition.