Python Loops: for, while, break, continue, and enumerate()
Loops are one of the most powerful features in Python. They allow us to repeat tasks, process collections, and control program flow without writing repetitive code.
1. for Loops - Iterating Over Collections
A for loop is used to iterate over a sequence (like a list, tuple, or string). It’s the most common loop in Python because it directly works with collections.
names = ["Alice", "Brian", "Jane", "David"]
for name in names:
print(f"Good morning, {name}")
print("For loop ended")
Output
Good morning, Alice
Good morning, Brian
Good morning, Jane
Good morning, David
For loop ended
Looping with range()
range() generates a sequence of numbers, often used in loops.
for n in range(5):
print(n)
for n in range(1, 11, 2):
print(n)
Output
0
1
2
3
4
1
3
5
7
9
Practical Examples
Multiplication table for 5
for i in range(1, 6):
print(f"5 X {i} = {5 * i}")
Output
5 X 1 = 5
5 X 2 = 10
5 X 3 = 15
5 X 4 = 20
5 X 5 = 25
Squares of numbers
for i in range(1, 6):
print(f"{i} squared is {i ** 2}")
Output
1 squared is 1
2 squared is 4
3 squared is 9
4 squared is 16
5 squared is 25
Summing numbers
numbers = [10, 20, 30, 40]
total = 0
for number in numbers:
total += number
print(f"Total: {total}")
Output
Total: 100
2. while Loops - Repeat Until a Condition is False
A while loop runs as long as a condition is True. It’s useful when you don’t know in advance how many times you’ll need to repeat.
count = 1
while count < 5:
print(f"Count: {count}")
count += 1
Output
Count: 1
Count: 2
Count: 3
Count: 4
Practical Examples
Password check
password = ""
while password != "lux2025":
print("You entered the wrong password")
password = input("Input password: ")
print("Access Granted")
Output
You entered the wrong password
Input password: 1234
You entered the wrong password
Input password: lux2025
Access Granted
Savings goal calculator
saving_goal = int(input("What is your saving goal (Ksh)? "))
monthly_savings = int(input("How much can you save per month (Ksh)? "))
total = 0
months = 0
while total < saving_goal:
total += monthly_savings
months += 1
print(f"Month {months}: Total so far = Ksh {total}")
print(f"It took {months} months to reach Ksh {total}")
Output
Month 1: Total so far = Ksh 1200
Month 2: Total so far = Ksh 2400
Month 3: Total so far = Ksh 3600
Month 4: Total so far = Ksh 4800
Month 5: Total so far = Ksh 6000
It took 5 months to reach Ksh 6000
3. break and continue - Controlling Loop Flow
break: exits the loop entirely.
continue: skips the current iteration and moves to the next.
transactions = [1500, 3000, 800, 12000, 450, 2700]
total = 0
for amount in transactions:
if amount > 10000:
print("Large transaction detected. Stopping...")
break
total += amount
print(f"Running total: {total}")
Output
Running total: 1500
Running total: 4500
Running total: 5300
Large transaction detected. Stopping...
4. enumerate() - Loop With Index
Sometimes you need both the item and its index. enumerate() provides this elegantly.
fruits = ['Mango', 'Banana', 'Orange']
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
Output
0: Mango
1: Banana
2: Orange
Real‑World Examples
1. Class Scores Analysis
scores = [78, 85, 91, 65, 72]
total = 0
above_70 = 0
for score in scores:
total += score
if score > 70:
above_70 += 1
average = total / len(scores)
print(f"Total: {total}")
print(f"Above 70 Scores: {above_70}")
print(f"Average: {average}")
Output
Total: 391
Above 70 Scores: 4
Average: 78.2
2. ATM PIN Validator
correct_pin = "4532"
attempts = 0
max_attempts = 3
while attempts < max_attempts:
pin = input("Enter your PIN: ")
attempts += 1
if pin == correct_pin:
print("Access granted! Welcome.")
break
else:
remaining = max_attempts - attempts
if remaining > 0:
print(f"Wrong PIN. {remaining} attempts left")
if attempts == max_attempts and pin != correct_pin:
print("Card Blocked. Please visit the branch")
Output
Enter your PIN: 1234
Wrong PIN. 2 attempts left
Enter your PIN: 9999
Wrong PIN. 1 attempts left
Enter your PIN: 4532
Access granted! Welcome.
Conclusion
Use for loops to iterate over collections or ranges.
Use while loops when repetition depends on a condition.
Use break to exit early and continue to skip iterations.
Use enumerate() when you need both index and value.
Loops are the backbone of automation in Python - they make repetitive tasks efficient and clean.
Top comments (0)