By now, we've worked with variables, user input, calculations and conditional statements. The next step is getting Python to repeat things for us. This is where loops come in.
Imagine having to print a receipt for 100 items. Without a loop, we would have to write the same code 100 times. A loop tells Python, essentially, keep doing this until you're done.
There are two main loops:
-
forloops - this is useful when we know what we want to go through or roughly how many times we want to repeat something. -
whileloops - this is for when we want to keep going while a condition is true.
Starting with a for loop
A for loop goes through items one at a time.
For example:
names = ["Alice", "Brian", "Jane", "David"]
for x in names:
print(f"Good morning, {x}")
print("For loop ended")
Instead of writing four separate print() statements, the loop handles all four names. The important part here is understanding what x actually represents. On the first round: x = "Alice" then Brian, then Jane, then David. So x is just a variable that temporarily holds the current item.
Here is the same idea with something more familiar:
fruits = ["Mango", "Banana", "Orange"]
for fruit in fruits:
print(f"I like {fruit}")
The loop doesn't need to know how many fruits there are. It simply goes through the list until there are no more items.
Using range()
Sometimes you don't have a list, you just want Python to repeat something a certain number of times. That's where range() comes in. For example:
for i in range(5):
print(i)
This prints:
0
1
2
3
4
One thing that stood out here is that 5 is not included. range(5) starts at 0 and stops before 5.
You can also choose where to start:
for n in range(1, 6):
print(n)
Output will highlight numbers 1, 2, 3, 4, 5
And you can also specify a step:
for n in range(1, 11, 2):
print(n)
Output being 1, 3, 5, 7, 9
Key note:
range(stop) range(start, stop) range(start, stop, step)
python
The stop value is always left out.
Loop Calculations
A loop becomes more useful when you actually do something with each value. For example, a multiplication table:
for i in range(1, 11):
result = 5 * i
print(f"5 x {i} = {result}")
You can also calculate squares:
for i in range(1, 6):
result = i ** 2
print(f"{i} squared is {result}")
The same pattern can be used for things like calculating totals.
The accumulator pattern
One example is adding transactions together.
transactions = [1500, 3000, 800, 12000, 450, 2700]
total = 0
for amount in transactions:
total += amount
print(f"Added Ksh {amount} Running total: Ksh {total}")
print()
print(f"Final Total: Ksh {total}")
The important thing here is: total = 0 comes before the loop. Then every time the loop runs, another transaction is added to the running total. So if the transactions are: 1500, 3000, 800 the total changes like this: 0 → 1500 → 4500 → 5300
An if inside a loop
Loops and conditionals can also work together. For example, you have a list of prices and want to classify each one:
prices = [250, 980, 120, 1500, 75]
for price in prices:
if price < 500:
show = "Affordable"
else:
show = "Expensive"
print(f"Price is {price} - {show}")
Here, the loop handles each price, while the if/else decides what to say about that particular price.
while loops
A for loop works well when you're going through a collection or have a known range. But what if you don't know how many times something should happen? For example, you might want to keep asking for a password until the correct one is entered.
password = ""
while password != "pi2025":
print("You entered the wrong password")
password = input("Enter password: ")
print("Access Granted")
The loop keeps checking: password != "pi2025". As long as that condition is True(password is not equal to pi2025), it continues. Once the password is correct, the condition becomes False and the loop ends.
One important thing to note here is that something inside the loop needs to change the condition.
For example:
count = 1
while count < 5:
print(f"Count: {count}")
count = count + 1
Without: count = count + 1, count would remain 1 forever and the loop would never finish. That's an infinite loop.
while True and break
Another one is: while True:. This creates a loop that will keep running unless we explicitly stop it. For example:
total = 0
while True:
entry = input("Enter Amount (or 'done' to finish): ")
if entry == "done":
break
amount = int(entry)
total += amount
print(f"Running total: Ksh {total}")
print(f"Final total: {total}")
The important part is: break which immediately exits the loop. This becomes useful when the user controls when the program should stop.
A small practice task can be a mini program for an ATM PIN: where the loop stops once the correct PIN is entered.
continue
continue is quite different from breakin the sense that break says: Stop the entire loop and continue says: Skip this round and move to the next one.
For example:
for n in range(1, 11):
if n % 2 == 0:
continue
print(n)
This skips even numbers, so only the odd numbers are printed.
enumerate()
Before enumerate(), if you wanted to number students, you would do something like:
students = ["Alice", "Brian", "Jane", "David"]
for i in range(len(students)):
print(f"{i + 1}. {students[i]}")
enumerate() now comes in and makes our code cleaner:
for number, student in enumerate(students, start=1):
print(f"{number}. {student}")
This gives us both:the position and the item
Here is a prcatical example for student scores:
scores = [78, 85, 45, 91, 35, 66, 38, 42]
for position, score in enumerate(scores, start=1):
if score < 50:
status = "FAIL"
else:
status = "PASS"
print(f"Student {position}: {score} {status}")
This is much easier to read when you need both the item and its position.
Nested loops
Nested loops are really interesting. You can put one loop inside another loop.
For example:
weeks = ["Week 1", "Week 2"]
exercises = ["Push-ups", "Squats", "Plank"]
for week in weeks:
print(week)
for exercise in exercises:
print(f" {exercise}")
The inner loop runs for every item in the outer loop. This shows that loops don't have to work independently. One loop can control or depend on another.
Putting It All Together: Mini Bank Loop
With this exercise, you can bring several of these ideas into one program. The task is to build a small bank menu with a starting balance of Ksh 10,000. The menu needs to keep appearing until the user chooses Exit.
Here's the complete program:
balance = 10000
while True:
print()
print("=== Mini Bank ===")
print("1. Check balance")
print("2. Deposit")
print("3. Withdraw")
print("4. Exit")
option = input("Choose option: ")
if option == "1":
print(f"Current balance: Ksh {balance}")
elif option == "2":
amount = float(input("Deposit amount: "))
balance += amount
print(f"Deposited Ksh {amount}. New balance: Ksh {balance}")
elif option == "3":
amount = float(input("Withdrawal amount: "))
if amount > balance:
print("Insufficient funds!")
else:
balance -= amount
print(f"Withdrawn Ksh {amount}. New balance: Ksh {balance}")
elif option == "4":
print("Thank you. Goodbye!")
break
else:
print("Invalid option. Try again.")
This small program uses quite a few things:
while True keeps the bank open
if/elif/else statements decide what should happen depending on the user's choice.
The balance is updated when money is deposited or withdrawn: balance += amount and: balance -= amount
There's also another if inside the withdrawal option to check whether the customer has enough money.
Finally, there is break which stops the program when the user chooses option 4.
Output:
To Sum Up
The main thing I took from this, is that loops are about automating repetition. A for loop is useful when going through items or a known range, while a while loop is useful when something should continue until a condition changes. break, continue, enumerate() and nested loops give more control over how those repetitions work. The Mini Bank project was a good example of why loops matter. Instead of writing a separate menu for every possible transaction, the program keeps running and responds to whatever the user chooses.

Top comments (0)