🔄 Quick Recap (Day 6)
You learned to make decisions with
if,elif, andelse.You handled user input and used comparisons to branch logic.
🎯 What You’ll Learn Today
How
forloops iterate over sequences.How
whileloops repeat while a condition holds.How to use
breakto exit a loop early.How to use
continueto skip to the next iteration.
📖 Overview: for Loops
A for loop repeats a block of code for each item in a sequence (list, string, range):
# Loop through a list of fruits
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)Output:
apple
banana
cherryfruitis a variable that takes each value fromfruitsin turn.Indentation shows the block that repeats.
Using range()
To loop a specific number of times:
for i in range(5): # 0,1,2,3,4
print(i)Output:
0
1
2
3
4📖 Overview: while Loops
A while loop repeats as long as a condition is true:
count = 0
while count < 3:
print("Count is", count)
count += 1Output:
Count is 0
Count is 1
Count is 2Be careful: if the condition never becomes false, the loop runs forever. Always update a variable inside the loop.
📖 Controlling Loops: break and continue
breakimmediately exits the loop:for num in range(10): if num == 3: break print(num)Output:
0 1 2continueskips to the next iteration:for num in range(5): if num % 2 == 0: continue print(num)Output:
1 3
🧙♂️ Take the Wand and Try Yourself
Create a file named
loop_practice.py.Write a
forloop that prints the square of numbers 1 through 5.Write a
whileloop that starts at 5 and counts down to 1.Inside the
forloop, usecontinueto skip printing when the square is divisible by 4.Inside the
whileloop, usebreakif the count reaches 2.
Solution Example (loop_practice.py):
# loop_practice.py
# For loop with continue
for i in range(1, 6):
square = i * i
if square % 4 == 0:
continue
print("Square of", i, "is", square)
# While loop with break
count = 5
while count >= 1:
if count == 2:
break
print("Counting down:", count)
count -= 1Run:
python loop_practice.pyExpected output:
Square of 1 is 1
Square of 3 is 9
Square of 5 is 25
Counting down: 5
Counting down: 4
Counting down: 3Once you see this output, you’ve mastered loops and their controls!
On Day 8: Lists, we’ll explore how to work with collections of data. See you there!