Exploring For Loops
This course explores Python’s For Loop and is part of a series of content designed to help you learn to program with the Python programming language.
- Explain the purpose of For Loops
- How to use For Loops
This course was designed for first-time developers wanting to learn Python.
This is an introductory course and doesn’t require any prior programming knowledge.
Hello, and welcome! My name is Ben Lambert, and I’ll be your instructor for this course. This course is part of a series of content designed to help you learn to program with the Python programming language.
Should you wish to ask me a specific question, you can do that with the contact details on screen. You can also reach support by using the email address: firstname.lastname@example.org. And one of our cloud experts will reply.
In this lesson we’ll explore Python’s for loop. Recall that loops are used to repeat a block of code. Python provides different types of loops which are used in different circumstances. Two of those loop types are: while loops and for loops. Both are used to repeat a block of code. While loops are used to repeat a code block based on some condition remaining True. And they stop when the condition becomes False, or the loop is broken.
For loops are used to bind a name to the next object in a collection. Such as a list, set, tuple, or dictionary. Each time the loop progresses it binds a name to the next object and then we can interact with that object. Imagine that we want to send a welcome email to a list of email addresses. Pretend that we created a function that will send an email. The how in this case isn’t important. Just know that it accepts an email address as input.
Using a for loop we can bind the name email_address to each email address in the list. The first time through the loop this name is bound to this first address. Then it can be passed to the send welcome email function. This function will be called once for each object in the list. This is the purpose of a for loop. To repeat a code block for some limited number of times. Let’s review the syntax used to define a for loop. Recall that we’re using for loops to bind a name to a value from a collection. For loops start with the lowercase word for and ends with a colon and a new line. After the word for is where we bind names. Then the keyword in: followed by a collection.
The code inside a for loop is indented using the standard indentation. This is the basic structure of a for loop. For each object in a collection repeat some code. This example starts by binding the name letters to a list of strings containing the letters a b c and d. Then the for-loop loops through each of the letters and binds the name letter to the next object. The built-in print function is used to display each letter in the console.
Since lists are ordered, when this loops through, the name letter will first be bound to a then b then c then d. And then the list will naturally stop. Recall that while loops continue to repeat while some condition is True. For loops have an implied stopping point. Which is at the end of the collection. However, there are times where we may want to stop a for loop, or move to the next object.
For this we can use the break and continue keywords. In this example the loop will start and bind to the letter a. The conditional is checked and since the current bound object of a doesn’t equal b it will move to this print function and print the letter a.
Next time around it will be bound to b. The condition is checked and since it’s True, this line is interpreted. The keyword break will stop the current loop entirely returning the flow to the code following the loop. Since we break out of the loop, we don’t see any other letters printed. The break keyword can be used when you know that you don’t require the loop to continue.
Here’s a similar example except we use the keyword continue. When this condition is True this continue statement will be interpreted and the loop will move to the next object in the collection.
When this runs it will print a c and d and skips printing b. Looping through a collection is a common task for developers.
- For each user in some database perform some task.
- For each invoice perform some calculation.
- For each email in the inbox mark as read.
Sometimes you’ll find that you need to repeat a block of code for some number of times. As opposed to each object in a collection.
Python provides a built-in function named range which enables us to repeat a for loop some number of times. The built-in range function accepts arguments to control the start and stop numbers. Each time this loop advances it will bind to an integer.
There’s another common use case with for loops which is the need to loop through a list and to know which loop index index we’re on. Python provides a built-in function named enumerate that can accept a collection as input. This function is a bit interesting because conceptually it returns a collection of tuples.
Recall that Python’s language syntax includes a feature called tuple unpacking. Tuple unpacking enables us to bind multiple names to corresponding objects inside a tuple. Unpacking also works with the name binding of for loops. Using this with the built-in enumerate function enables us to bind one name to the loop’s counter and another to the value.
This example will print out the index and its corresponding value. These built-in functions have they’re use cases. However, those are specific to the problems being solved by the code. So don’t worry if you can’t imagine use cases. As you begin reading other people’s code, you’ll see more real world examples.
Okay, this seems like a natural stopping point. Here are your key takeaways for this lesson:
- The purpose of a for loop is to repeat a code block for some limited amount of times. For example: for each object in a list.
- For loops are defined with the for and in keywords. Where the first portion of the definition specifies the name bindings the second portion specifies the collection.
- For loops will naturally stop on their own when all objects have been looped through. They can also be stopped using the break keyword.
- The built-in range function can be used to loop for a specific number of times.
- The built-in enumerate function can be used to loop through a collection producing the value and the loop index.
That's all for this lesson. Thanks so much for watching. And I’ll see you in another lesson!
Ben Lambert is a software engineer and was previously the lead author for DevOps and Microsoft Azure training content at Cloud Academy. His courses and learning paths covered Cloud Ecosystem technologies such as DC/OS, configuration management tools, and containers. As a software engineer, Ben’s experience includes building highly available web and mobile apps. When he’s not building software, he’s hiking, camping, or creating video games.