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:

Unlock This Lesson for Free - No Payment Required!

If you like to keep on reading, register now!

  • Learn CCNA, CCNP and CCIE R&S. Explained As Simple As Possible.
  • Get Instant Access to this Full Lesson, Completely for Free!
  • Unlock More to Read. More Lessons Added Every Week!
  • Content created by Rene Molenaar (CCIE #41726)
2153 Sign Ups in the last 30 days

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