Python for Loop

In the last lesson, we learned about the Python Ternary Operator. Now let’s repeat the same job without writing the same code again and again.

Let’s Talk About Repetition

Imagine we have to write β€œHello” on a whiteboard 100 times.

Would we write it 100 times by hand? That would take forever. And our hand would hurt.

No. We would find a way to do it faster. Maybe we use a stamp. Or we print it. Or we get a machine to do it.

Computers are great at repetition. They never get tired. They never get bored. They can do the same thing a million times without complaining.

That is what loops are for.

What Is a Loop in Python?

A loop is a way to repeat something.

Instead of writing the same code again and again, we write it once. And we tell Python: β€œDo this 10 times” or β€œDo this for each item in this list.”

Python has two main types of loops:

  • for loop β€” repeat a specific number of times, or for each item in a collection
  • while loop β€” repeat as long as a condition is true

In this article, we will learn about the for loop.

What Is a Python for Loop?

A for loop goes through a sequence of items. One by one. And for each item, it does something.

Think of it like this. We have a list of names. We want to say hello to each person.

We could write:

print("Hello, Alex")
print("Hello, Sam")
print("Hello, John")

But what if we have 100 names? That is a lot of lines.

With a for loop, we write it once.

names = ["Alex", "Sam", "John"]
for name in names:
print(f"Hello, {name}")

Output

Hello, Alex
Hello, Sam
Hello, John

See? The loop goes through each name. And for each one, it prints a greeting.

That is the power of for.

The Structure of a Python for Loop

for variable in sequence:
# do something
  • for β€” the keyword that starts the loop
  • variable β€” a name we choose. It holds the current item.
  • in β€” the keyword that connects the variable to the sequence
  • sequence β€” the thing we want to loop through
  • : β€” the colon
  • Then indented code β€” what to do for each item

The indented code runs once for each item in the sequence.

Using range() in Python for Loop

The most common way to loop a specific number of times is with range().

for i in range(5):
print(i)

Output

0
1
2
3
4

Wait. Why does it start at 0? And why does it stop at 4?

Because range(5) gives us numbers from 0 to 4. Not including 5.

That is a bit weird at first. But it is how Python works. The end number is not included.

Let me show us.

for i in range(3):
print("Hello")

Output

Hello
Hello
Hello

It ran 3 times. Because range(3) gives 0, 1, 2. That is 3 numbers.

So range(n) runs the loop n times.

range() with Start and End

We can also give range() a start and end.

for i in range(2, 6):
print(i)

Output

2
3
4
5

It starts at 2. And goes up to but not including 6.

So range(2, 6) gives 2, 3, 4, 5.

range() with Step

We can also give it a step. The step is how much to increase each time.

for i in range(0, 10, 2):
print(i)

Output

0
2
4
6
8

It starts at 0. Goes up to 10 (not including). And jumps by 2 each time.

We can also go backwards.

for i in range(5, 0, -1):
print(i)

Output

5
4
3
2
1

It starts at 5. Goes down to 0 (not including). And steps by -1 each time.

Looping Through a String in Python

We can loop through a string. Each character is an item.

for letter in "Python":
print(letter)

Output

P
y
t
h
o
n

See? It goes through each character one by one.

Looping Through a List in Python

We can loop through a list. Each item is an item.

fruits = ["apple", "banana", "orange"]
for fruit in fruits:
print(fruit)

Output

apple
banana
orange

Python for Loop: A Real-Life Example

Let’s calculate the sum of numbers from 1 to 10.

total = 0
for i in range(1, 11):
total += i
print(f"Sum: {total}")

Output

Sum: 55

Let me explain what happened.

  • total starts at 0.
  • The loop goes from 1 to 10.
  • Each time, it adds the current number to total.
  • After the loop, total is 55.

That is a common pattern. We start with something. And we update it in the loop.

Another Example β€” Multiplication Table

number = 7
for i in range(1, 11):
print(f"{number} x {i} = {number * i}")

Output

7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35
7 x 6 = 42
7 x 7 = 49
7 x 8 = 56
7 x 9 = 63
7 x 10 = 70

That is a multiplication table. And we wrote it with just three lines.

The Loop Variable in Python for Loop

The variable in the for loop is just a name. We can call it anything.

for i in range(3):
print(i)
for x in range(3):
print(x)
for num in range(3):
print(num)

All three do the same thing. The name does not matter.

But it is good to use a meaningful name. For numbers, i is common. For items, use the item name.

for fruit in fruits:
print(fruit)

That is clearer than:

for x in fruits:
print(x)

Common Mistakes with Python for Loop

Mistake 1: Forgetting the Colon

Here is a mistake we all make. We write the for line and forget the colon.

for i in range(5)
print(i)

Error! Missing colon.

So what do we do? We add the colon.

for i in range(5):
print(i)

Mistake 2: Forgetting Indentation

for i in range(5):
print(i)

Error! The print needs indentation.

So what do we do? We indent the code inside the loop.

for i in range(5):
print(i)

Mistake 3: Using the Wrong Variable

for i in range(5):
print(x) # Error! x is not defined

The loop variable is i. So we use i. Not x.

So what do we do? We use the correct variable name.

for i in range(5):
print(i)

Mistake 4: Thinking range(5) Gives 1 to 5

for i in range(5):
print(i)

This gives 0 to 4. Not 1 to 5.

If we want 1 to 5, we use:

for i in range(1, 6):
print(i)

Next, we will learn about the Python while Loop, which repeats code while a condition remains true.