<aside> 🌳 Real-life Example Imagine you have a box of chocolates, and you want to share one with each of your five best friends. Instead of saying, "Give a chocolate to Amy, then give a chocolate to Bob, then give a chocolate to Charlie,..." and so on, it would be so much easier to say, "Give a chocolate to each of my five best friends."
That's what a for
loop does in coding! It lets you do something many times without writing it over and over.
</aside>
Video Explanation
What is a for loop?
A for
loop is like a mini-instruction manual that tells the computer: "Do this task for each item in this group."
How can you use it?
Let's look at an example. Imagine you have many lines that look almost the same, like:
m[7][0] = (21, 0, 89)
m[7][1] = (21, 0, 89)
m[7][2] = (21, 0, 89)
m[7][3] = (21, 0, 89)
m[7][4] = (21, 0, 89)
m[7][5] = (21, 0, 89)
m[7][6] = (21, 0, 89)
m[7][7] = (21, 0, 89)
This can be shortened using a loop:
for column in range(0, 8):
m[7][column] = (21, 0, 89)
Here's what's happening:
range(0, 8)
gives us a group of numbers: 0, 1, 2, ..., 6, 7.for
loop says: "For each number in this group, set column
to the next number and do the task inside the loop."m[7][column] = (21, 0, 89)
where column
is replaced by the number.So, the computer sets each pixel m[7][0]
, m[7][0]
, …, m[7][0]
to your desired color.
Using this idea, you can tackle programming pixels in multiple rows at once:
for column in range(0, 8):
m[7][column] = (21, 0, 89)
m[6][column] = (32, 0, 133)
And so on...
You’ll find many patterns like above, where you can use a loop to replace repeated lines.