A loop is a programming structure that is used to execute a block of code repeatedly. In Python, loops are essential for automating repetitive tasks, processing collections of data, and creating efficient, concise code. Rather than writing the same instructions over and over, loops let you write them once and let the computer repeat it as many times as necessary. This article covers how loops work in python, but more importantly, why they matter.
Problems Loops Solve
Imagine you need to print the numbers 1 through 5. Without loops you would write:
print(1)
print(2)
print(3)
print(4)
print(5)
That works. Now imagine printing 1 through 1,000 or a million or a number you do not know in advance, because it depends on how many rows are in a file a user uploads.
This is where approach breaks down completely. You can't write code for a quantity you do not know yet, and you shouldn't write a thousand near identical lines even when you do.
A loop replaces all:
for i in range(1,6):
print(i)
Change 6 to 10000001 and the code doesn't get any longer. That is the fundamental purpose of a loop, the length of your code stops depending on the size of your data.
Loops Separate Logic From Volume
When writing a loop, you are separating what should happen from how many times it should happen.
Example:
for customer in customers:
print(customer)
The print statement is written once. The volume (however many customers exist) is handled independently. If the business grows from 10 to 10,000 customers the code does not change.
For Loop
A for loop is used to iterate over a sequence like (list, tuple, string or range). It executes a specific number of times based on how many items are in the sequence.
students = ["Amina","Brian","Njeri","Faith","Otieno","Wanjiku","Fatuma"]
for student in students:
print(f"Good morning, {student}"
# output
Good morning, Amina
Good morning, Brian
Good morning, Njeri
Good morning, Faith
Good morning, Otieno
Good morning, Wanjiku
Good morning, Fatuma
The variable student acts as a placeholder that automatically updates to the next item in the list during each iteration of the loop.
Range()
range() is a function that is used to generate a sequence of numbers. The range() function takes up three arguments range(start, stop, step).
-
With One Argument
range(stop): The range will start at 0 and count up by 1 and stops before it reaches the stop number.
for i in range(5):
print(i)
# Output
0
1
2
3
4
-
With Two Arguments
range(start, stop):
for i in range(3,8):
print(i)
# Output
3
4
5
6
7
-
With Three Arguments
range(start, stop, step):
The third number tells Python how much to add to the number during each round of the loop.
for i in range (1,11,2):
print(i)
# Output
1
3
5
7
9
- Counting Backwards:
You can count down by using a negative step value. When counting backwards the start value should be greater than the stop value.
for i in range (5,0,-1):
print(i)
# Output
5
4
3
2
1
You can loop through everything that holds multiple items:
# strings prints character by character of that word
for char in "hello":
print(char)
# dictionaries, prints key and value together
for key, value in person.items():
print(key, value)
Calculations inside a loop:
transcations = [1500, 3000, 800, 12000, 450, 2700]
total = 0
for amount in transcations:
total = total + amount
print(f" Added Ksh {amount} Running total: Ksh {total}")
print(f"Final total: Ksh {total}")
Output
Added Ksh 1500 Running total: Ksh 1500
Added Ksh 3000 Running total: Ksh 4500
Added Ksh 800 Running total: Ksh 5300
Added Ksh 12000 Running total: Ksh 17300
Added Ksh 450 Running total: Ksh 17750
Added Ksh 2700 Running total: Ksh 20450
Final total: Ksh 20450
Using if statement inside the loop:
prices = [250,980,120,1500,75]
for price in prices:
if price >= 500:
category = 'Expensive'
else:
category = 'Affordable'
print(f"Ksh {price} - {category}")
Output
Ksh 250 - Affordable
Ksh 980 - Expensive
Ksh 120 - Affordable
Ksh 1500 - Expensive
Ksh 75 - Affordable
Nested for loop:
days = ["Monday", "Tuesday","Wednesday"]
periods = ["period 1","period 2", "period 3"]
for day in days:
print(f"---{day} ---")
for period in periods:
print(f" {period}")
print()
Output
---Monday ---
period 1
period 2
period 3
---Tuesday ---
period 1
period 2
period 3
---Wednesday ---
period 1
period 2
period 3
Enumerate()
enumerate() is a built-in function that is used to loop through a sequence while keeping track of the index and value of each item. By default, enumerate() starts counting at 0, therefore, you need to pass the start argument initialized at 1.
Example:
students = ["Bob","John","Njeri","Wanjiku"]
for pos, student in enumerate(students, start=1):
print(f"{pos}. {student}")
Output
1. Bob
2. John
3. Njeri
4. Wanjiku
While Loop
A while loop repeats as long as a condition stays true. Use it when the number of iterations is not known ahead of time.
Example
count = 1
while count < 5:
print(f"Count: {count}")
count += 1 # Increases count by 1 each time
Output
Count: 1
Count: 2
Count: 3
Count: 4
A while loop stops if something inside it eventually makes the condition false. If nothing does, it runs forever:
count = 1
while count < 5:
print(f"Count: {count}")
# forgot to increment count - this never ends
This is the classic infinite loop. It's the main reason to prefer a for loop whenever you're iterating over a known collection because the loop will terminate.
password = ''
while password != 'secret'
password = input('Enter the password: ')
print('Access granted')
You can't write this with a for loop, because you have no idea how many attempts the user will need. The loop keeps going until the condition changes.
Using if statement inside while loop:
score = -1
while score < 0 or score > 100:
score = int(input("Enter score (0-100): "))
if score < 0 or score > 100:
print("Invalid! Score must be between 0 and 100")
print(f"Valid score accepted: {score}")
Controlling The Flow: break and continue
Sometimes you need to exit early or skip an iteration. The break statement stops the loop completely and immediately exits out of it. It lets you stop work as soon as you have your answer, rather than pointlessly processing the rest.
Example:
scores = [78,85,91,35,66,55,42]
for score in scores:
if score < 40:
print(f"First failing score found: {score}")
break
print(f" {score} --> OK")
print("Search complete")
Output
78 --> OK
85 --> OK
91 --> OK
First failing score found: 35
Search complete
The continue statement skips the rest of the remaining iteration and jumps to the next cycle. It used to filter out things you want to ignore.
Example:
for num in range(1,6):
if num % 2 == 0:
continue #skips even numbers
print(num)
Output:
1
3
5
Using break & continue together:
sales = [1200, -500, 800, 0, 950, 300]
total = 0
for sale in sales:
if sale < 0:
continue
if sale == 0:
break
total += sale
print(f"Total valid sales: Ksh {total}")
The code skips -500 but stops when it gets to 0.
Output
Total valid sales: Ksh 2000
Conclusion
Loops matter because they are the point where your code stops being a fixed list of instructions and starts being a process. They automate repetitive tasks, saves time and prevent messy code. Learning to write clear, correct loops isn't just one topic among many in Python; it's the skill that lets you write programs that handle real-world data at real-world scale.
Top comments (0)