HOLIDAY SALE! Save 50% on Membership with code HOLIDAY50. Save 15% on Mentorship with code HOLIDAY15.

10) Conditionals and Loops Lesson

Python For Loop

10 min to complete · By Martin Breuss

In the previous lesson, you learned about the concept of looping and encountered Python's for loop, which allows you to do definite iteration.

Colorful illustration of a light bulb

Info: The iteration is called definite because the length of your iterable--- your string for example ---defines how often the loop will execute.

How Does a For Loop Work

Now, you'll pick apart the syntax of a Python for loop to understand each part that makes it up.

You'll start by writing out a small for loop that iterates over a string:

for char in "hello":
    print(char)

Can you guess what this code outputs?

Colorful illustration of a light bulb

Info: Thinking about what the output of a code snippet will be before running it in your interpreter is a great way to train your coding skills. It forces your brain to process the code and gives you a chance to uncover misunderstandings if your guess turns out to be wrong.

When you run this code snippet, you'll see that it prints out each character of "hello" in a new line. This works because strings are collections of single characters.

Anatomy of a For Loop

Looking at the example code snippet above, you'll notice that the for loop consists of a minimum of two lines of code:

  1. Opening Statement: for char in "hello":
  2. Body: print(char)

Opening Statement

The first line makes up the statement that opens up the body of your for loop. You can deconstruct this line even further into five separate parts:

  1. for keyword (for): This is the same in each for loop. It's the signal for Python that what follows should be interpreted as a for loop.
  2. Iterator (char): This is a variable name. You can call it anything, and you're encouraged to name it descriptively for what you are looping over. In this case, you named it char, which is short for character. This describes well what the variable will refer to in the body of your for loop. In every iteration of the loop, the variable char will point to a new value, which is the current item in your collection. In this case, it'll be each subsequent character of the word "hello".
  3. Membership Operator (in): This is also the same in each for loop. You've encountered the membership operator before, and here, it's used as a part of the for loop construct to point to every item in a collection.
  4. Iterable ("hello"): This is the collection you are iterating over. Any object that allows you to loop over it is called an iterable. In your case, this is the string "hello".
  5. Colon (:): The colon is Python's indicator that the first line of your for loop is ending. Which also means it opens up the body of the for loop.

The first line of your for loop always consists of the same elements, even though the variable name you give to the iterator, as well as the value of the iterable, will be different.

Two fingers in glove - Photo by https://unsplash.com/@diana_pole Diana Polekhina on Unsplash

Body

The second line of code makes up the body of your for loop. Its body can contain many more lines of code than just one. The code in the body makes up the code logic that you apply to the elements in your collection, which means that most of it will be different for each for loop you write.

Still, there are a few important and repeating elements that you can deconstruct:

  1. Indentation ( ): Each line of code needs to be indented exactly four spaces. Indentation carries meaning in Python, and in this case, it tells Python that whatever is indented is part of the for loop's body. If you forget to indent a line, Python will not consider it part of your for loop.
  2. Code Logic (print()): Any code that you want to run once per element in your collection. In this example, you're just printing the value of the char variable, but this could be any modification or calculation you want to write.
  3. Iterator Variable (char): Remember the iterator variable you named char in line one of your for loop? This is where you get to use this variable. This variable gets overwritten with a new value each time the for loop loops back to the start. Since it'll run once for each item in your iterable, your variable char will therefore point to each item in that iterable one after another.

Within the body of your for loop, you can write code logic that does something with each element in your collection because you get access to each of them one by one.

For Loop Practice

  • Apply a string method to each of the characters in a string.
  • Apply alternating string methods to every second character in your string.
  • Create a for loop that prints out aLtErNaTiNg CaPs from the word you iterate over.

Go ahead and practice writing some for loops. Get in some practice and wrap your head around this concept; it's really powerful and important!

Mocking Spongebob Loop Meme

Once you're done goofing around, go ahead and do it once again. This lesson is about looping after all! :)

for loops allow you to do definite iteration in Python, and they are common and intuitive to use once you've practiced them for a while. So far, you've only iterated over strings, but what if you want to work with collections of numbers? You'll learn how to do that with the range() function in the next lesson.

Colorful illustration of a light bulb

Additional Resources

Summary: Python For Loop

  • A for loop allows you to loop over the elements of a collection.
  • The elements are called iterators and the collection is called an iterable.
  • A for loop consists of the opening statement and the body
  • The opening statement defines the variable name for your iterators, which iterable to loop over, and ends with a colon
  • The body contains all code logic that you want to apply in the loop

Anatomy of Opening Statement

  1. for
  2. Iterator
  3. Membership Operator
  4. Iterable
  5. Colon

Anatomy of the Body

  1. Indentation
  2. Code Logic
  3. Iterator Variable