In the previous lesson, you learned about the concept of looping and encountered Python's for loop, which allows you to do definite iteration.
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?
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:
- Opening Statement:
for char in "hello": - 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:
forkeyword (for): This is the same in eachforloop. It's the signal for Python that what follows should be interpreted as aforloop.- 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 itchar, which is short for character. This describes well what the variable will refer to in the body of yourforloop. In every iteration of the loop, the variablecharwill 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". - Membership Operator (
in): This is also the same in eachforloop. You've encountered the membership operator before, and here, it's used as a part of theforloop construct to point to every item in a collection. - 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". - Colon (
:): The colon is Python's indicator that the first line of yourforloop is ending. Which also means it opens up the body of theforloop.
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.
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:
- 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 theforloop's body. If you forget to indent a line, Python will not consider it part of yourforloop. - 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 thecharvariable, but this could be any modification or calculation you want to write. - Iterator Variable (
char): Remember the iterator variable you namedcharin line one of yourforloop? This is where you get to use this variable. This variable gets overwritten with a new value each time theforloop loops back to the start. Since it'll run once for each item in your iterable, your variablecharwill 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
forloop 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!
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.
Additional Resources
- A Bite Of Python: The
forLoop - Think Python: String Traversal
Summary: Python For Loop
- A
forloop allows you to loop over the elements of a collection. - The elements are called iterators and the collection is called an iterable.
- A
forloop 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
for- Iterator
- Membership Operator
- Iterable
- Colon
Anatomy of the Body
- Indentation
- Code Logic
- Iterator Variable