Python for Loop
Table of Contents
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:
forloop β repeat a specific number of times, or for each item in a collectionwhileloop β 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, AlexHello, SamHello, JohnSee? 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 somethingforβ the keyword that starts the loopvariableβ a name we choose. It holds the current item.inβ the keyword that connects the variable to the sequencesequenceβ 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
01234Wait. 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
HelloHelloHelloIt 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
2345It 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
02468It 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
54321It 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
PythonSee? 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
applebananaorangeπ― 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: 55Let me explain what happened.
totalstarts at 0.- The loop goes from 1 to 10.
- Each time, it adds the current number to
total. - After the loop,
totalis 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 = 77 x 2 = 147 x 3 = 217 x 4 = 287 x 5 = 357 x 6 = 427 x 7 = 497 x 8 = 567 x 9 = 637 x 10 = 70That 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 definedThe 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.