Previous Lesson: Lesson 20: List Comprehensions in Python

For loops in Python is one of the most important features of Python that we can use in our code. It is so efficient that even if we only have a small chunk of code, it can run as many times as we want it to.

For Loops with a List

Create a new file: ex18.py. And type this in:

So instead of accessing each and every element from our list, we are gonna use for loops. And to start a for loop, we use the word for. Afterwards, we this a name which in our case, dog. Then we do a colon (:) just like what we do on if-statements and functions.

Then, we give it something to do, we made it print dog. But, of course, it would not literally print the word “dog”. Let’s run it:

There we go! You might get confused with the dog. But I’m telling you, it is just a name for our elements in the list. Additionally, we can change it into whatever name we want. I’ll show you. Type these in:

Owrayt! We used burger, pizza, and whatever. When we run this, all three results should be exactly the same:

Tada! You see? You don’t have to worry about the name after the for because we can use any word for it.

for loops with range

Now let’s say that you don’t have a list but you just want to loop through some chunk of code by certain amount of times. Let’s first make a room and review what range can give us:

We make a variable called nums and then we will range over 1 through 10 in a format of a list. Run this:

Okay. “But I don’t want this printed out like that. I just want to enumerate those numbers in a non-list format like this:”

Look, if we enjoy typing (WET), we’ll do it like this:

Eew! This is so disgusting to type because what if I wanted to print out 1 to 1000 in my Terminal? Would I really type print(“”) a thousand times? You wouldn’t, would you? Remember, we’re in front of a computer, so there’s always a better way and an easier way to accomplish things. I know that we can use for loops, but how? Type this in:

Before you run this, I just want you to have that appreciation for for loops. Go back and compare this chunk of code to our previous one. Let’s see if we’ll get what we want:

Nice. Can we do it up to 1000? Let’s do it!

Run:

Boom! Yes baby! I love for loops! Unlike ranges, we can have any big number with for loops–now you can do 1 to a billion. Although that might take you forever, you can always use the Ctrl + C or control + C for stopping the loop.

And that’s it for loops in Python. In the next lesson, we’ll talk about another kind of loop in Python called the while loop. Let’s go check this out!

Next Lesson: Lesson 22: While Loops in Python

4 Replies to “Lesson 21. For Loops in Python”

Leave a Reply

Your email address will not be published.