Lesson Contents
Python supports two loop types:
- While Loop
- For Loop
With the Python for loop, we can “loop” through a sequence and execute code for each item in the sequence. Going through items in a sequence is called iteration. The sequence can be a string, list, tuple, dictionary, etc.
For Loop
Let’s start with an example:
We start with “for” and then we specify the name of a new variable. This variable represents the item inside the sequence of each iteration. In the example above, I use the variable “fw”. This code iterates through the items on the list and prints each item.
Break Statement
With the break statement, we can stop the for loop before it has iterated all the items in our sequence. Here’s how it works:
Our code prints FW1 and FW2 but breaks out of the loop when variable “fw” equals FW3.
Continue Statement
With the continue statement, we stop the current iteration and continue with the next item. Here is an example:
The code above skips the current item when our variable “fw” equals string “FW2”.
Else Statement
The else statement specifies code you want to run when the loop is finished:
Nested Loop
This one is interesting. We can also run a loop within a loop. Take a look at the following code: