Check out a free preview of the full Practical Guide to Python course
The "Loops" Lesson is part of the full, Practical Guide to Python course featured in this preview video. Here's what you'd learn in this lesson:
Nina demonstrates "for" loops. The range() and enumerate() functions simplify the syntax when looping over large amounts of data. Tuple unpacking is useful when looping over tuples and dictionaries.
Transcript from the "Loops" Lesson
[00:00:00]
>> Now let's go back and talk about for loops and range and enumerate and then we'll come back to the last part of this exercise afterwards. So we are talking about loops. Loops in Python don't necessarily look like they do in other programming languages. If you write JavaScript, Java or some other languages, you might be used to loops that look something like this, where you define a for, you define a starting point, you define what number you're looping to, and then define a condition that helps progress that starting value to the ending condition.
[00:00:50]
Looping in python is a lot simpler and cleaner and actually a lot of other programming languages have borrowed from Python syntax and now incorporate some of these nicer looping structures. So in the past we had used this in keyword to test if an item was inside of a sequence, but when we combine the end keyboard with the for keyword in can be used to indicate that you are looping over each item in a sequence.
[00:01:24]
So the syntax for this is for a single item, and that's gonna be a temporary variable name. In items, which is a sequence, followed by a colon, you're gonna start a new line and then indent under to loop in that for loop. And again, if you're in the repple, you'll need to press Enter again in order to see the results.
[00:01:56]
Instead, I'm going to make a new Python file called loops.pi. And we can start up here. So if I exit my repple here and I run this Python file in the terminal, I will see the color is red, green, blue and orange. And I'm printing out the value of color, which I define right here inside of my loop.
[00:02:41]
Something interesting that I want to point out is that loops don't have the same scope as functions. So here the for loop was updating the value of color each time that we looped over the loop. When we are outside of the loop, this variable color still exists. And the value of that variable is the last value that was in the list.
[00:03:15]
So something to be mindful of when you're thinking about scope. There's also a range function that lets you generate a range of numbers. You can pass in one value into it. If you want to see what is actually generated, you're going to need to pass this range into a list because this is what's called a generator type in Python.
[00:03:41]
Python 2 used to be more inefficient in Python 3, if you passed a large number in here, it's not going to create a new data structure where the numbers from one to that very large number are also stored in memory at once. So if you want to take a look at this, let's pass it into the list constructor, and it would tell you what this would generate all at once.
[00:04:08]
But generally because you're going to be using this range to loop over something, you don't necessarily have to have that whole range in memory. You only care about what that value is while you're in the loop and what the next value might be. And that's an optimization that allows Python to save memory.
[00:04:28]
You could also pass in two numbers, where this would be the starting point and this would be the ending point. The ending point is not inclusive. So you can go ahead and use range along with the for loop. And that will go ahead and print out each item in this range.
[00:04:58]
Now, if you need to get a handle on an index, let's say that I have these colors. If you needed to print out both the name of the color and the position that it was in, don't go back to your old style for loops. You don't need to declare a variable to keep track of i and then increment i and then print that out.
[00:05:24]
There's a shortcut in Python for that called enumerate, and the enumerate function, you pass it in a list or set and it will return a tuple. So if we passed in the value of enumerate to look at it. We'll see that it returns a list of tuples where the first item is zero.
[00:05:52]
So that's the index and the second item is what was contained in our list. So this matches a position with a value. And then you can use that tuple unpacking that we saw earlier, inside of a for loop. In order to get both of these values at once.
[00:06:14]
So I can say for index color in enumerate colors and then I can print out the index, And the color. Without having to keep track of an i without incrementing it without creating any extra variables. The use of the enumerate function is one of those things that differentiates beginners to Python, who don't necessarily understand the core concepts like all of you do with programmers and Python who are more intermediate.
[00:06:58]
If I spot somebody using the enumerate function, I know that they have a pretty good understanding of what's going on under the hood and what pythonic code looks like. Now remember, if we want to loop over a dictionary, we need to be mindful that by default, a dictionary just gives us back the keys.
[00:07:23]
So we need to explicitly asked for both keys and values. So I'm going to grab this dictionary right here with some hex colors. If I were going to loop over, This, I would just get the keys. If I wanted to loop over keys and values at the same time, I would need to call hex_colors.items to get back the keys and the values.
[00:08:01]
And look, this is returning a list of tuples that means that we can use tuple unpacking. So I can now say for key comma value in hex_colors.items. Print the key, print something else and then print the value. So this is how I loop over both the key and the value in a dictionary at once and use tuple unpacking to get the key into a variable named key and the value into a variable name value, so that I could then use them in my loop.
[00:08:48]
Python also has while loops, and for those, you will need to use some sort of counter. I'm not going to jump into while loops because you all have some programming experience. And so I expect that while loops look pretty similar to what they might in your programming language of choice.
[00:09:11]
I will say that the syntax for a while loops looks something like this. So I can say maybe Val = 0 and then say while Val < 5, print the value and then increase the value by one, either by saying Val equals now val+1 or saying Val+=1. And that will go ahead and run a while loop.
[00:09:43]
So for a while loops you just do while and an expression that evaluates to true or false. When you're doing while loops, make sure that you will eventually have a condition or this is false otherwise your program will run for forever. If you need to short circuit your loop, you can use a return statement to break out of it.
[00:10:08]
So let's say I have some names. If I wanted to loop over these names and stop when I found the target value so I can say if name is equal to Stan. Oops, sorry, what I wanted to say was that you would want to use this in a function.
[00:10:52]
Let's do this a little bit differently. Let's save return_target and pass in the name of a target. And now we could do the same for loop and make sure that it is indented correctly. Oops, sorry. If name is equal to the target, we're going to return the name.
[00:11:30]
Let me make sure that is indented correctly. So now I can return target and it will print Stan or I can make a new target of Nina. And once that target is found the function will return. So that's a way of short circuiting a loop, a different way of short circuiting loops is with break and continue.
[00:11:58]
Those are more advanced concepts that I'm not going to cover but there is an optional chapter here in the course website where you can follow through on those
Learn Straight from the Experts Who Shape the Modern Web
- In-depth Courses
- Industry Leading Experts
- Learning Paths
- Live Interactive Workshops