Lesson 13. Looping With for
We're gonna loop back to talking about loops (see what I did there?).
The reason for the step back is because there are objects in Python that work with for loops in ways that make iterating through complex objects really easy. List, tuples, and dictionaries are three of those objects. I had to introduce them first before I showed you how to loop through them with for.
For loops are another basic concept in computer science and you will find the for construct in most programming languages. For is my preferred way of looping.
Technically, the for loop construct in Python is not like the for found in other programming languages. In other languages, you usually define a condition that is checked against an incrementing value like we saw back when we were talking about while.
In Python, the for loop is for iterating over sequences. Those sequences can be the three complex data types that we are already familiar with. Later, we will see that sequences can include things like file names which comes in handy when you need to do work on a bunch of files in a folder.
Just like in while, for can be used with break and continue to control the flow of the execution.
for Syntax
Examples
Example #1 Looping Over A List
The variable that you use in your for loop can be referred to in the code block. It represents the current value of the object you are iterating through.
You can define the variable yourself, however, in certain use cases, the variable needs to be a Python reserved word. We will take a look at that when we get to looking at looping over files in a directory.
Example #2 Looping Over A Tuple
Example #3 Looping Over A Dictionary
Example #4 Looping Over A Predefined Range
You can use for like you would in other languages using the range() method. The range method lets you define a range of values to loop over. The method has three parameters that define the range of values. The method can be called with one to three parameters.
It is important to remember that the upward bound of the range is NOT inclusive. In other words, if you set an upward bound of 5, the stopping value will be 4.
Now you try it!
Don't copy and past. Type the code yourself!
Last updated