Backend
Python: Loops
Mary Ngure DEV Community
4 views
One thing I've started noticing as I learn Python is that computers are really good at doing repetitive tasks.
Imagine being asked to print the numbers from 1 to 100 manually. Or process the scores of 50 students one by one.
That would be exhausting for a human.
For Python, however, repeating a task is exactly what loops are designed for.
Loops allow us to run a block of code multiple times without having to write the same code over and over again.
What is a Loop?
A loop tells Python:
"Keep doing this until we've finished."
For example, instead of writing:
print(1)
print(2)
print(3)
print(4)
print(5)
We can use a loop:
for number in range(1, 6):
print(number)
Output:
1
2
3
4
5
Much cleaner.
for Loops
A for loop is useful when we want to go through a sequence of items. It repeats KNOWN number of times, or over a collections of items.
That could be:
numbers
strings
lists
other collections of data
For example:
names = ["Mary", "John", "Ann"]
for name in names:
print(name)
Output:
Mary
John
Ann
Python takes each item from the list, stores it temporarily in name, and runs the indented code.
Using range()
range() is particularly useful when working with numbers.
for number in range(1, 6):
print(number)
This prints numbers from 1 to 5.
One thing to remember is that the ending number is not included.
It stops before the number
So:
range(1, 6)
means:
1, 2, 3, 4, 5
while Loops
A while loop works a little differently.
Instead of going through a known sequence, it keeps running as long as a condition is true.
For example:
count = 1
while count <= 5:
print(count)
count += 1
Output:
1
2
3
4
5
Here, Python keeps asking:
Is count <= 5?
As long as the answer is True, the loop continues.
The line:
count += 1
is important because it changes the value of count.
Without it, the condition would remain true and we'd create an infinite loop.
When Should I Use for vs while?
A simple way I'm thinking about it is:
Use a for loop when you know what you're going through.
for name in names:
print(name)
Use a while loop when you want to continue until a condition changes.
while savings < goal:
savings += monthly_savings
Both repeat code, but they are useful in different situations.
break: Stop the Loop
Sometimes we don't want a loop to continue all the way through.
That's where break comes in.
break immediately stops the loop.
For example:
for number in range(1, 11):
if number == 6:
break
print(number)
Output:
1
2
3
4
5
When Python reaches 6, the break statement stops the loop.
A practical example is asking a user to enter scores until they type "done":
scores = []
while True:
score = input("Enter score or done: ")
if score.lower() == "done":
break
scores.append(int(score))
print(scores)
Here, while True creates a loop that keeps running, while break gives us a way to stop it.
continue: Skip an Iteration
continue is different from break.
Instead of stopping the loop completely, continue tells Python:
"Skip this one and move to the next iteration."
For example, suppose we want to print numbers from 1 to 5 but skip 3:
for number in range(1, 6):
if number == 3:
continue
print(number)
Output:
1
2
4
5
The loop didn't stop. It simply skipped the iteration where number was 3.
So a useful way to remember them is:
break → Stop the loop
continue → Skip this iteration
enumerate(): Get the Position and the Value
Another useful concept I've come across is enumerate().
When looping through a list, sometimes we want both:
The item
Its position in the list
For example:
names = ["Mary", "John", "Ann"]
for index, name in enumerate(names):
print(index, name)
Output:
0 Mary
1 John
2 Ann
By default, enumerate() starts counting from 0.
We can change that by specifying start=1:
names = ["Mary", "John", "Ann"]
for number, name in enumerate(names, start=1):
print(number, name)
Output:
1 Mary
2 John
3 Ann
This is especially useful when creating reports, rankings, menus, or numbered lists.
Practical Example: Student Scores
Let's bring these concepts together.
Suppose we have a list of student scores and want to generate a simple report:
scores = [85, 72, 64, 91, 48]
for number, score in enumerate(scores, start=1):
if score >= 50:
result = "Pass"
else:
result = "Fail"
print(f"Student {number}: {score} - {result}")
Output:
Student 1: 85 - Pass
Student 2: 72 - Pass
Student 3: 64 - Pass
Student 4: 91 - Pass
Student 5: 48 - Fail
Here we're combining loops, enumerate(), conditionals, and f-strings in one small program.
Practical Example: Savings Goal
A while loop can also be useful for something like tracking savings.
goal = float(input("What is your savings goal? "))
monthly_savings = float(input("How much can you save per month? "))
total = 0
months = 0
while total < goal:
total += monthly_savings
months += 1
print(f"It will take you {months} months to reach your goal.")
print(f"You will have saved {total:.2f}.")
The loop continues adding the monthly savings until the total reaches the goal.
This is a good example of why while loops are useful: we don't necessarily know how many times the loop needs to run beforehand.
A Simple Mental Model
I'm finding it helpful to think about loops like this:
Start → Repeat → Check → Repeat or Stop
For a for loop:
Take an item → Do something → Take the next item → Continue
For a while loop:
Check condition → Do something → Check again → Stop when false
And then we have:
break → Stop completely
continue → Skip this round
enumerate() → Get the position + the item
Key Takeaways
The main things I'm taking away from loops are:
for loops are useful for going through sequences of items.
while loops repeat code while a condition remains true.
break stops a loop completely.
continue skips the current iteration.
enumerate() gives us both the position and the item when looping through a sequence.
Loops become even more powerful when combined with conditionals, lists, and functions.
The more I practice loops, the more I see how much repetitive work Python can handle for me. Instead of writing the same instructions repeatedly, I can define the process once and let the computer do the repetition.
Read original: https://dev.to/maryngure/python-loops-29k8
← Previous
Everyone Said 'Just Go Serverless.' I Ran a Long-Lived Node Process — Here's What That Bought
Next →
My Comment Section Designed My Next Experiment. Then It Made Me Freeze My Predictions.
Related
From Physical Racks to Intelligent Modules: How the Meaning of Infrastructure Has Fundamentally Shifted
Backend
4
Dev.to (EN Zone)
Python Functions: Why They changed My code
Backend
4
Dev.to (EN Zone)
Four Ways to Survive a Network Split
Backend
6
Dev.to (EN Zone)
The fifteen ways a Google Play subscription breaks quietly
Backend
5
DEV Community
Comments0
No comments yet — be the first