We have already seen how to do loops with “while”, and now we will learn how to use the “for” statement.

The way you write a for is the following: “for i in x:”, after that you fill up its guts with what action you want it to perform.

The “in” part makes it so that the “for” gets along especially well with ranges, list, tuples and dictionaries. What it does is that it makes your program search for a special something in the insides of another something, for example a range or a list, and then do something to that something it found, or simply perform an action according to it.

We can convine this with other stuff, like ifs for example:

L [1, 0, 1, 0, 0, 0, 1, 1, 0, 1, 5]

For I in L:

If (I = 1):

Print (“yes”)

Elif (I = 0):

Print (“no”)

Else:

Print (“Get yourself together!”)

This program will check every value within the list “L”, and depending on its magnitude it will perform an action, printing “yes” if the value is one, “no” if the value is zero, or “Get yourself together!” if it finds another value.

Using for statements gets fun when you start working with calculations or “searches” with big amounts of data, it will save your butt a lot of pain.

The main difference between a “while” and a “for” is that the while will run definitively if given the chance, but the “for” fill always have a beginning and an end, since you work with finite things like lists and ranges. A “for” CAN be infinite, but only if the range you are using is infinite itself.

CC BY 4.0 For loops with “for” by juansalvadorfernandez is licensed under a Creative Commons Attribution 4.0 International License.