Introduction
When I started learning Python, one thing that made programming feel more powerful was discovering I didn't have to write the same piece of code over and over
At first, repetition in programming seemed straightforward. If I wanted Python to display five numbers, I could write five print() statements. But what happens when I want to display 100 numbers? Or process 1,000 records from a dataset?
Writing the same code repeatedly would quickly become impractical.
This is where loops come in.
Loops let us tell Python to repeat a block of code instead of writing the same instructions multiple times. They're one of those concepts that seem simple at first but become incredibly useful as your programs grow more complex.
Whether you're processing a list of customers, checking a collection of scores, validating user input, searching through data, or automating repetitive tasks, loops are likely to become a regular part of your Python code.
Python gives us two main types of loops: the for loop and the while loop. We also have break and continue, which allow us to control how loops behave, and enumerate(), which makes it easier to track an item's position while looping through a collection.
Understanding the Idea Behind Loops
Before getting into the different types of loops, it's worth understanding what a loop is actually trying to solve.
Imagine that we want Python to print the numbers from 1 to 5.
We could write:
print(1)
print(2)
print(3)
print(4)
print(5)
There is nothing technically wrong with this code, but we're repeating ourselves.
Python gives us a better way:
for number in range(1, 6):
print(number)
The output is:
1
2
3
4
5
Instead of writing five separate instructions, we've described a pattern and allowed Python to handle the repetition.
This is essentially what a loop does: it lets us write a block of code once and have Python execute it multiple times, following a set rule.
That rule could be based on a collection of values, a range of numbers, or a condition that remains true.
for Loops: Going Through a Collection
The first type of loop we'll look at is the for loop.
A for loop is commonly used when we want to go through items in a list, tuple, string, or range.
For example, suppose we have a list of fruits:
fruits = ["Mango", "Banana", "Orange"]
We can use a for loop to go through each fruit:
for fruit in fruits:
print(fruit)
The output is:
Mango
Banana
Orange
What's happening here is actually quite simple.
Python takes the first item from the list and stores it temporarily in the variable fruit. It then executes the indented code:
print(fruit)
After that, Python moves to the next item and repeats the process.
The important thing to understand is that fruit represents the current item during each iteration of the loop.
We could call that variable almost anything:
for item in fruits:
print(item)
The result would be the same. The name we choose needs to make sense for what the variable represents.
Using for Loops With range()
Another common way of using for loops is with Python's range() function.
For example:
for number in range(1, 6):
print(number)
This produces:
1
2
3
4
5
One thing that initially confused me about range() was why 6 doesn't appear in the output.
The reason is that the ending value in range() is not included.
So:
range(1, 6)
means:
Start at 1 and stop before reaching 6.
We can also control the amount by which the number changes each time:
for number in range(2, 11, 2):
print(number)
The output is:
2
4
6
8
10
Here, Python starts at 2, stops before 11, and increases the value by 2 each time.
This is useful for generating even numbers, creating countdowns, or repeating an operation a specific number of times.
Looping Through Strings
One interesting thing about Python is that we can loop through more than just numbers and lists.
We can also loop through a string:
word = "Python"
for letter in word:
print(letter)
The output is:
P
y
t
h
o
n
Python processes the string one character at a time.
This can be useful when we need to inspect individual characters.
For example, we could count how many times the letter "a" appears in a word:
word = "banana"
count = 0
for letter in word:
if letter == "a":
count += 1
print(count)
The output is:
3
The loop checks each character in "banana". Every time it finds "a", the count increases by one.
This is a simple example, but it demonstrates an important idea: loops let us perform the same operation on every item in a sequence.
while Loops: Repeating While a Condition Is True
The second major type of loop in Python is the while loop.
A while loop works a little differently from a for loop. Instead of going through a collection, it keeps running as long as a certain condition is True.
For example:
number = 1
while number <= 5:
print(number)
number += 1
The output is:
1
2
3
4
5
The process starts with:
number = 1
Python then checks:
number <= 5
Because 1 is less than or equal to 5, the condition is true, so the loop runs.
It prints the number and then increases it:
number += 1
Python checks the condition again and continues the iteration.
Eventually, number becomes 6. At that point, 6 <= 5 is false, so Python stops the loop.
The important thing to remember about a while loop is that something inside the loop usually needs to change so the condition can eventually become false.
For example, this code would cause a problem:
number = 1
while number <= 5:
print(number)
The loop never changes number, so it remains 1. Since 1 <= 5 is always true, Python keeps printing 1.
This is known as an infinite loop.
Adding:
number += 1
allows the loop to move toward its stopping condition.
Choosing Between for and while
A simple way to think about the difference is that a for loop is usually useful when you're going through a collection or a known sequence of values.
For example:
students = ["Ian", "Mary", "John"]
for student in students:
print(student)
We know exactly what we're processing: the items in the students list.
A while loop is often more appropriate when we don't know exactly how many times something needs to happen.
For example, suppose we want to keep asking a user for a password until they enter the correct one:
password = ""
while password != "python123":
password = input("Enter password: ")
print("Access granted.")
We don't know whether the user will enter the correct password on the first attempt or the tenth. The loop continues while the condition is true.
This distinction becomes easier to understand with practice, and eventually choosing between for and while starts to feel natural.
Controlling Loops With break
Sometimes we want to stop a loop before it has finished processing everything.
Python gives us the break statement for this purpose.
Consider:
for number in range(1, 11):
if number == 6:
break
print(number)
The output is:
1
2
3
4
5
When Python reaches 6, it encounters break and immediately leaves the loop.
It's almost like telling Python:
"We've found what we need. Stop here."
This can be particularly useful when searching through data:
students = ["Brian", "Mary", "Ian", "John", "Sarah"]
for student in students:
if student == "Ian":
print("Student found!")
break
print(f"Checking {student}...")
Once Python finds "Ian", there's no reason to keep searching through the remaining names.
Skipping an Iteration With continue
While break stops a loop completely, the continue statement does something different.
It tells Python to skip the current iteration and move to the next one.
For example:
for number in range(1, 6):
if number == 3:
continue
print(number)
The output is:
1
2
4
5
When Python reaches 3, it encounters continue. Instead of executing the rest of the code for that iteration, Python moves directly to the next number.
A simple way to remember the difference is:
break → stop the loop completely
continue → skip this iteration
This is useful when we want to ignore certain values but still process everything else.
For example:
scores = [78, -5, 85, -2, 91]
for score in scores:
if score < 0:
continue
print(score)
The output is:
78
85
91
The negative scores are skipped, but the loop continues processing the remaining scores.
Using enumerate() With Loops
Some situations come up frequently when working with lists.
Suppose we have:
students = ["Ian", "Mary", "John"]
and we want to print each student's name while also tracking their position in the list.
We could do this:
for i in range(len(students)):
print(i, students[i])
This works, but Python provides a cleaner and more readable solution through enumerate():
for index, student in enumerate(students):
print(index, student)
The output is:
0 Ian
1 Mary
2 John
The enumerate() function gives us both the index and the item during each iteration.
We can also tell enumerate() to start counting from a different number:
students = ["Ian", "Mary", "John"]
for number, student in enumerate(students, start=1):
print(number, student)
The output becomes:
1 Ian
2 Mary
3 John
This is especially useful when creating numbered lists:
items = ["Rice", "Sugar", "Milk"]
for number, item in enumerate(items, start=1):
print(f"{number}. {item}")
The output is:
1. Rice
2. Sugar
3. Milk
Instead of manually creating and updating a counter, enumerate() handles the counting for us.
Putting Everything Together
The real value of these concepts becomes more obvious when we start combining them.
Suppose we have a list of student scores and want to display scores that are at least 40. We also want to show the student's position in the list.
We could write:
scores = [78, 45, 91, 32, 85]
for number, score in enumerate(scores, start=1):
if score < 40:
continue
print(f"Student {number}: {score}")
The output is:
Student 1: 78
Student 2: 45
Student 3: 91
Student 5: 85
The for loop goes through the scores; enumerate() gives us the student's number and score. The if statement checks the score, and continue allows us to skip scores below 40.
This is where Python starts becoming more interesting. The concepts we learn individually begin to work together to solve actual problems.
Why Loops Matter in Python
At first, loops might seem like nothing more than a way to print numbers repeatedly.
But their usefulness goes further than that.
Imagine working with a dataset containing thousands of customers. You might need to examine each record, calculate something, search for specific values, or identify records that meet certain conditions.
You wouldn't want to write separate instructions for every customer.
Instead, you describe the operation once and let Python repeat it.
The same principle applies to processing transactions, checking scores, reading files, validating information, generating reports, and automating repetitive tasks.
Final Thoughts
When I think about learning loops, I don't think the most important lesson is simply memorizing the syntax of for and while.
The bigger lesson is learning to identify patterns of repetition.
A for loop allows us to move through a collection or sequence one item at a time. A while loop allows us to keep acting while a condition remains true. break gives us a way to stop a loop completely when we've reached the point we need, while continue lets us skip a particular iteration without stopping the loop.
Then there's enumerate(), which makes working with both the position and value of items much easier.
At first, these concepts can feel like separate pieces of Python syntax that you need to memorize. But with enough practice, something changes.
Loops are just one piece of the Python puzzle, but they're an important one. Once you are comfortable with them, you're no longer simply telling Python what to do once.
You're learning how to tell Python how to do something repeatedly, intelligently, and efficiently.
Top comments (0)