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:
firewalls = ["FW1","FW2","FW3"]
for fw in firewalls:
print(fw)
Will show this output:
FW1
FW2
FW3
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:
firewalls = ["FW1","FW2","FW3"]
for fw in firewalls:
if fw == "FW3":
break
print(fw)
Will show this output:
FW1
FW2
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:
firewalls = ["FW1","FW2","FW3"]
for fw in firewalls:
if fw == "FW2":
continue
print(fw)
Will show this output:
FW1
FW3
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:
ip_addresses = ["192.168.1.1","192.168.1.2"]
for ip in ip_addresses:
print(ip)
else:
print("Completed the loop.")
Will show this output:
192.168.1.1
192.168.1.2
Completed the loop.
Nested Loop
This one is interesting. We can also run a loop within a loop. Take a look at the following code: