Part 2 of a 3-part series. Real code from my Python learning journey, written for beginners.
Your Code Can Make Decisions and Repeat Work
A program that always runs top to bottom is limited. The moment you add if statements and loops, your code can decide, repeat, skip, and stop. In this article I show you the exact patterns I used while building my own projects, including the login system and menu from my mini bank. Each snippet is small, runnable, and explained line by line.
If you landed here first, you only need to know variables, input(), and f-strings. That is covered in Part 1: Python Basics for Beginners. Otherwise, let us go.
This part covers:
- if/elif/else and nested if
- while loops
- for loops
- continue and break
- enumerate()
- nested loops
1. if/else: Making Decisions
The if statement runs code only when a condition is true:
username = input("username: ")
if username == "admin":
password = input("password: ")
if password == "admin123": # nested if, an if inside an if
print("Login successful")
else:
print("Incorrect password")
else:
print("Unknown username")
If the username is not "admin", Python jumps straight to the final else. If it is, the program enters the block and finds a second if: the nested if. Only now does it ask for a password. Notice the inner block is indented further, because in Python indentation defines which block a line belongs to.
The pattern: if for the first check, elif for extra checks, else as the catch-all. Part 1's transaction limiter used the same chain.
WHY NESTED IF MATTERS
The password is only asked after the username passes. Code runs top to bottom, so order equals security.
Mini-challenge: lock after 3 wrong passwords
MINI-CHALLENGE
Allow only 3 wrong password attempts, then lock the account. Spoiler: you will need a while loop, which is next.
How to try it: solve it on your own first, then compare with the solution below.
Solution (no peeking before you try):
attempts = 0
while attempts < 3:
password = input("password: ")
if password == "admin123":
print("Login successful")
break
else:
attempts += 1
print(f"Incorrect. {3 - attempts} attempts left")
if attempts == 3:
print("Account locked")
The counter starts at 0, grows by 1 on every wrong password, and the loop ends when it reaches 3. A counter plus a condition, the pattern behind most loops.
2. while Loops: Repeat Until Something Changes
A while loop repeats as long as its condition stays true. Perfect for input validation, where you keep asking until the answer is valid:
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}")
score starts at -1 on purpose, so the loop body always runs at least once. A valid input like 85 fails the condition on the next check and the loop exits; an invalid 150 prints a message and loops again. The only way out is a valid score.
A while loop also makes a great countdown:
start = 5
while start > 0:
print(start)
start -= 1 # subtract 1 each time, an assignment operator
print("Blast off!")
Each pass prints the number, then subtracts 1. When start hits 0, the condition is false and the loop stops.
GOLDEN RULE
If the loop condition never becomes false, the loop never ends. Always change something inside the loop, or you get an infinite loop that freezes your program.
3. for Loops: Walk Through a List
A for loop visits every item of a list in order, no counter needed:
transactions = [500, 1200, -200, 8500, 15000, -500, 3000]
total = 0
for i in transactions:
if i < 0:
continue # skip negative ones, keep looping
print(f"Transaction {i}")
total += i
print(f"Total: Ksh {total}")
Python hands each value to i in turn. When i is -200, the continue statement skips the rest of the body and jumps to the next value, so negatives are never printed or added. That is how you filter a list.
continue vs break
- continue skips the current item and moves to the next.
- break stops the whole loop immediately.
Here is break in action:
transactions = [500, 1200, -200, 8500, 15000, -500, 3000]
for i in transactions:
if i > 10000:
print(f"Large transaction flagged: Ksh{i}")
break # stop everything
print(f"Ksh {i} OK")
The loop prints each transaction as OK until it hits 15000. That is over 10000, so it flags it and stops. No more items are processed.
| Keyword | What it does | When to use it |
|---|---|---|
continue |
Skips the current item and moves to the next | To filter: skip the bad, keep the good |
break |
Stops the whole loop immediately | To find something and stop early |
REMEMBER
Use continue to filter. Use break to find something and stop. You will use both in the mini bank in Part 3.
4. enumerate(): Numbered Lists for Free
Need a numbered menu or exam paper? enumerate() gives you the position and the item together, in one loop:
students = ["Bob", "Nelly", "Mogere", "Gesare"]
for pos, student in enumerate(students, start=1):
print(f"{pos}. {student}")
Without enumerate you would need a counter variable you manually increment. With it, Python does the bookkeeping: each iteration unpacks the position and the item. Output: 1. Bob, 2. Nelly, 3. Mogere, 4. Gesare.
PRO TIP
start=1 makes the numbering begin at 1 instead of 0. Without it, your menu starts at 0.
5. Nested Loops: A Loop Inside a Loop
Loops can live inside loops. Here is a mini timetable:
days = ["Monday", "Tuesday", "Wednesday"]
periods = ["Period 1", "Period 2", "Period 3"]
for day in days:
print(f"-------{day}------")
for period in periods: # inner loop runs fully for each day
print(f" {period}")
print()
The outer loop picks a day and prints its header. The inner loop then runs completely for that day, printing all three periods, before the outer loop moves on. That is 3 days x 3 periods = 9 prints.
Part 2 Recap
You should now be comfortable with:
- Making decisions with if/elif/else, including nested if
- Repeating code with while and for loops
- Controlling loops with continue and break
- Numbering lists with enumerate()
- Combining loops in nested structures
COMING NEXT
Packaging code into reusable functions. Part 3 covers functions plus two real projects, a receipt generator and a mini bank, that use everything from this part.
Continue to Part 3
Continue to Part 3: Python Functions and Mini Projects for Beginners
Bookmark this part and share your own loop examples in the comments.





Top comments (0)