Day 4: Loops — Making Programs Repeat
🐍 Day 4: Loops — Making Programs Repeat
1. Learning Objectives
By the end of Day 4, you will be able to:
- Use
forloops to iterate over sequences - Use
whileloops to repeat code while a condition holds - Control loop flow with
breakandcontinue - Use the
elseclause on loops for clean completion checks - Avoid the dreaded infinite loop
2. Concept Explanation
2.1 Why Loops? — Doing Things More Than Once
Programs often need to repeat actions. Without loops, you'd have to write the same code over and over:
# Without loops — pain!
print("Student 1")
print("Student 2")
print("Student 3")
# ... imagine 1000 students
Loops let you write the action once and repeat it as many times as needed.
2.2 The for Loop — Iterating Over Sequences
The for loop takes each item in a sequence, one at a time, and runs its block with that item.
# Basic for loop
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
Output:
apple
banana
cherry
How it works: The variable fruit is assigned "apple", then the block runs; then "banana", block runs; then "cherry", block runs; then the loop ends.
range() — the loop counter's best friend:
range(n) generates numbers from 0 to n-1. Very useful for repeating a block a specific number of times.
for i in range(5):
print(i)
Output:
0
1
2
3
4
range(start, stop, step) gives finer control:
for i in range(2, 10, 3): # 2, 5, 8
print(i)
Looping over strings:
for char in "Hello":
print(char)
Output: H, e, l, l, o (each on new line)
Looping over other sequences we'll learn later: lists, tuples, dictionaries, sets, files — all work with for.
2.3 The while Loop — Repeat While Condition is True
A while loop checks a condition before each iteration. If it's True, the block runs; if False, the loop ends.
count = 1
while count <= 3:
print(count)
count += 1
Output:
1
2
3
⚠️ Danger: If the condition never becomes
False, you get an infinite loop. Your program will run forever (pressCtrl+Cto stop).
# Infinite loop — don't run unless you want to see it!
x = 1
while x > 0:
print(x)
x += 1 # never becomes <=0
When to use while vs for:
- Use
forwhen you know how many times to iterate (or iterate over an existing collection). - Use
whilewhen you need to loop as long as a condition is true, and you don't know the number of iterations in advance (e.g., waiting for user input).
2.4 Loop Control: break and continue
Sometimes you need to exit a loop early or skip an iteration.
break — immediately exits the entire loop (no more iterations).
for i in range(10):
if i == 5:
break
print(i)
# Output: 0 1 2 3 4 (stops before 5)
continue — skips the rest of the current iteration and jumps to the next one.
for i in range(5):
if i == 2:
continue
print(i)
# Output: 0 1 3 4 (2 is skipped)
Think of break as "stop the loop entirely" and continue as "skip this one and go to next".
2.5 The else Clause on Loops — Did It Finish Naturally?
Python allows an else block after a for or while loop. It executes only if the loop completed normally (i.e., not interrupted by break).
for i in range(5):
print(i)
else:
print("Loop finished without break.")
Output: 0 1 2 3 4, then the message.
If a break occurs, the else block is skipped:
for i in range(5):
if i == 3:
break
print(i)
else:
print("This won't print")
# Output: 0 1 2
This is particularly useful for search loops: if you find the item, break; if not, the else runs to say "not found".
2.6 Nested Loops
You can put loops inside loops:
for i in range(3):
for j in range(2):
print(f"i={i}, j={j}")
This prints 3×2=6 combinations.
Be careful: nesting increases total iterations dramatically. A loop inside a loop that both run 1000 times gives 1,000,000 iterations.
3. Code Examples
Example 1: Multiplication Table
# Print 5's multiplication table
n = 5
for i in range(1, 11):
print(f"{n} x {i} = {n * i}")
Example 2: Password Attempts with while
correct = "python123"
attempts = 3
while attempts > 0:
guess = input("Enter password: ")
if guess == correct:
print("Access granted.")
break
attempts -= 1
print(f"Wrong. {attempts} attempts left.")
else:
print("Account locked.")
Example 3: Filtering with continue
# Print only odd numbers from 1 to 10
for num in range(1, 11):
if num % 2 == 0:
continue
print(num)
4. Hands-On Exercises
Exercise 1: Countdown
Ask the user for a number, then print a countdown from that number to 0 using a while loop.
Exercise 2: Sum of Numbers
Using a for loop, calculate the sum of all numbers from 1 to 100 (inclusive). Print the sum.
Exercise 3: FizzBuzz
Print numbers from 1 to 30. For multiples of 3, print "Fizz" instead of the number. For multiples of 5, print "Buzz". For numbers that are multiples of both 3 and 5, print "FizzBuzz".
Exercise 4: Prime Checker
Ask for an integer >1. Use a loop to test if it's prime (divisible only by 1 and itself). Print "Prime" or "Not prime". (Hint: use % and break)
Exercise 5: Menu Repeater
Write a program that repeatedly displays a menu:
1. Say Hello
2. Show Date (just print a placeholder like "2026-05-06")
3. Quit
Keep showing the menu until the user chooses 3. Use while and break.
5. Applied Challenge Task 🏗️
Number Guessing Game
Build a game where the computer thinks of a random number between 1 and 100, and the player has to guess it.
- Generate a secret number using
random.randint(1, 100). (You'll needimport randomat the top.) - Give the player 7 attempts.
- After each guess, tell the player if the guess is too high, too low, or correct.
- If the player guesses correctly, congratulate them and show how many attempts they used.
- If they run out of attempts, reveal the secret number.
- Use
breakto end the loop when they win.
Example output:
I'm thinking of a number between 1 and 100. Can you guess it? You have 7 tries.
Guess 1: 50
Too high!
Guess 2: 25
Too low!
Guess 3: 37
Correct! You got it in 3 tries. 🎉
Stretch goals:
- After the game, ask if they want to play again (loop the whole game).
- Validate that the guess is a number between 1–100.
- Track and print the player's guess history after they win/lose.
6. Brief Review Summary
| Concept | Key Points |
|---|---|
for loop |
Iterates over a sequence (list, string, range, etc.) |
while loop |
Repeats while condition is True |
break |
Exits the loop immediately |
continue |
Skips to the next iteration |
else on loops |
Runs only if loop finished without break |
| Infinite loop | Condition never becomes False — use Ctrl+C to interrupt |
| Nested loops | Loop inside loop — beware of performance |
7. Preview of Next Topic — Day 5
Tomorrow we'll dive into one of the most important concepts in programming:
- Functions — defining reusable blocks of code
- Parameters & arguments — passing data into functions
- Return values — sending data back
- Scope — where variables live and how they're accessed
🎯 Your Action Items for Day 4:
- ✅ Complete all 5 exercises
- ✅ Complete the Number Guessing Game challenge
- ✅ Experiment with an infinite loop and kill it with
Ctrl+C - ✅ Try the
elseclause on loops with both success andbreakcases
Comments
Post a Comment
Leave us your comments here...