Skip to main content

For Loops

Since the beginning, all the code you have written has been done manually.

What if you have similar code that you want to repeat multiple times?

This is where for loops come in.

info

For loops allow you to run a block of code multiple times.

Let's say that you want to print the numbers from 1 to 10.

You can do it by copy and pasting:

repetitive.py
print(1)
print(2)
print(3)
...
print(10)

Doesn't it seem awfully boring and repetitive to do it this way?

If you had to print all of the numbers from 1 to 1000, you would have to write new print() statements 1000 times!

info

A for loop goes through every item in a list from beginning to end and does something with each item.

For example,

for item in [1, 2, 3]:
print(item)
Output: 1 2 3

Now let's try printing 1 to 10 again. We can do this:

for number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]:
print(number)
Output: 1 2 3 4 5 6 7 8 9 10

We've just condensed the code from the first example into two lines.

Generally, you write a for loop like this:

for a in b:
# do something

Where a can be any name you want and b is the variable name to a list.