Python For Loop

Python supports two loop types:

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:

The code above could be used to connect to different Cisco network devices and execute multiple show commands. The first loop iterates over the “ip_addresses” list and the second loop iterates over the “show_commands” list.

Conclusion

You have learned how to use the Python for loop:

  • The for loop iterates through a sequence and executes code for each item in the sequence.
  • The break statement allows you to stop the loop before it iterates over all items.
  • The continue statement skips the current iteration and continues with the next item.
  • The else statement runs code when the loop finishes.
  • You can use a nested for loop to run a loop within a loop.

I hope you enjoyed this lesson. If you have any questions, please leave a comment.


Ask a question or start a discussion by visiting our Community Forum