4
Lesson 4: Loops and Iteration
Repeating actions efficiently
Learning Objectives
By the end of this lesson, students will:
- Use for loops to repeat code a specific number of times
- Apply while loops for conditional repetition
- Master the range() function for loop control
- Use break and continue statements effectively
Skills Developed:
- Automation and efficiency thinking
- Pattern recognition
- Loop design and optimization
Lesson Content
1 For Loops and Range Function (20 minutes)
Key Concepts:
- • For loops repeat code a specific number of times
- • range() generates sequences of numbers
- • Loop variable takes each value in the sequence
- • Indentation defines what's inside the loop
# Basic for loop
for i in range(5):
print("Count:", i)
# Output: 0, 1, 2, 3, 4
# Range with start and stop
for num in range(1, 6):
print("Number:", num)
# Output: 1, 2, 3, 4, 5
# Range with step
for even in range(0, 11, 2):
print("Even number:", even)
# Output: 0, 2, 4, 6, 8, 10
Instructor Notes:
Emphasize that range(5) gives 0-4, not 1-5. Show how this relates to robot movements - "move forward 5 times" or "check sensor 10 times".
2 While Loops (15 minutes)
While Loop Characteristics:
- • Repeats while a condition is True
- • Must have a way to eventually become False
- • Risk of infinite loops if condition never changes
- • Good for unknown number of repetitions
# Basic while loop
count = 0
while count < 5:
print("Count is:", count)
count = count + 1 # Important!
# User input loop
password = ""
while password != "robot123":
password = input("Enter password: ")
print("Access granted!")
# Sensor reading simulation
distance = 100
while distance > 10:
print("Moving forward, distance:", distance)
distance = distance - 15 # Simulate movement
print("Obstacle detected! Stopping.")
Warning:
Always ensure the loop condition will eventually become False! Show example of infinite loop and how to stop it (Ctrl+C).
3 Loop Control: Break and Continue (15 minutes)
Control Statements:
break:
- • Exits the loop immediately
- • Skips remaining iterations
- • Continues after the loop
continue:
- • Skips rest of current iteration
- • Goes to next iteration
- • Loop continues running
# Break example - find first even number
for num in range(1, 20):
if num % 2 == 0:
print("First even number:", num)
break
# Continue example - skip odd numbers
for num in range(1, 11):
if num % 2 == 1:
continue # Skip odd numbers
print("Even number:", num)
# Robot obstacle avoidance
for step in range(100):
obstacle = input("Obstacle? (y/n): ")
if obstacle == "y":
print("Obstacle detected! Stopping.")
break
print("Step", step, "- Moving forward")
4 Nested Loops and Patterns (15 minutes)
Nested Loop Concepts:
- • Loop inside another loop
- • Inner loop completes fully for each outer loop iteration
- • Useful for 2D patterns, grids, and complex repetition
- • Think of robot grid navigation
# Simple pattern
for row in range(3):
for col in range(5):
print("*", end="")
print() # New line after each row
# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f"{i} x {j} = {i*j}")
# Robot grid search
for x in range(3):
for y in range(3):
print(f"Checking position ({x}, {y})")
Hands-On Activity (25 minutes)
Project: Robot Movement Simulator
Students will create a program that simulates robot movement patterns and obstacle detection.
Requirements:
- • Use a for loop to simulate 10 movement steps
- • Use a while loop for obstacle detection
- • Include break statement for emergency stop
- • Create a pattern using nested loops
- • Add user interaction for manual control
- • Include battery level that decreases with each step
🤖🔄 How to Code This Project (Choose Your Platform):
📱 Pythonista 3:
- Open Pythonista 3
- Tap "+" → "Empty Script"
- Name it "robot_simulator.py"
- Type the code below
- Tap ▶️ to run
- Interact with prompts
Tip: Try different inputs (y/n/stop)
🤖 Pydroid 3:
- Open Pydroid 3
- Tap "+" → "Python file"
- Name it "robot_simulator.py"
- Type the code below
- Tap ▶️ yellow play button
- Interact with prompts
Tip: Watch battery decrease with each step
💻 PC/Mac:
- Open IDLE or editor
- Create new file
- Save as "robot_simulator.py"
- Type the code below
- Press F5 to run
- Interact with prompts
Tip: Test emergency stop feature
# Robot Movement Simulator
print("🤖 Robot Movement Simulator")
battery = 100
position = 0
# Main movement loop
for step in range(10):
print(f"\nStep {step + 1}:")
print(f"Battery: {battery}%")
print(f"Position: {position}")
# Check for low battery
if battery < 20:
print("⚠️ Low battery! Returning to base.")
break
# Move forward
move = input("Move forward? (y/n/stop): ")
if move == "stop":
print("🛑 Emergency stop activated!")
break
elif move == "y":
position += 1
battery -= 10
print("🚀 Moving forward...")
else:
print("⏸️ Staying in place")
battery -= 2
# Search pattern demonstration
print("\\n🔍 Search Pattern:")
for row in range(3):
for col in range(4):
print("📍", end=" ")
print()
Assessment & Homework
Quick Check (In Class):
- • Can student write both for and while loops?
- • Do they understand range() function?
- • Are they using break/continue appropriately?
- • Can they create simple nested loops?
Homework Assignment:
Automated Factory System
Create a program that simulates an automated factory production line. Use loops to process batches of items, implement quality control checks, and handle equipment maintenance cycles.