Beginner Level â€ĸ Lesson 3

🔄 Repeating Actions

âąī¸ 45 minutes 📚 Beginner đŸŽ¯ Loops
🔄

Repeating Actions

Learn how to make your programs repeat actions using loops - this makes your code shorter and more powerful!

What are Loops?

Loops let you repeat code multiple times without writing it over and over. Think of it like repeating a song - instead of singing it 10 times manually, you just say "repeat 10 times"!

💡 Real-World Example: When you scroll through Instagram, the app uses a loop to show each post. Without loops, you'd have to write code for every single post!

The FOR Loop

The for loop repeats code a specific number of times. It's perfect when you know exactly how many times you want to repeat something.

Basic FOR Loop

for i in range(5): print("Hello!") print("This is loop number", i)

What happens: The code inside the loop runs 5 times. The variable i counts from 0 to 4.

Output:

Hello! This is loop number 0 Hello! This is loop number 1 Hello! This is loop number 2 Hello! This is loop number 3 Hello! This is loop number 4

Understanding range()

The range() function creates a sequence of numbers. Here's how it works:

đŸ”ĸ

range(5)

Creates numbers: 0, 1, 2, 3, 4

(5 numbers, starting from 0)

đŸ”ĸ

range(1, 5)

Creates numbers: 1, 2, 3, 4

(starts at 1, stops before 5)

đŸ”ĸ

range(0, 10, 2)

Creates numbers: 0, 2, 4, 6, 8

(starts at 0, stops before 10, steps by 2)

The WHILE Loop

The while loop repeats code as long as a condition is True. It keeps going until the condition becomes False.

WHILE Loop Example

count = 0 while count < 5: print("Count is:", count) count = count + 1 print("Loop finished!")

What happens: The loop runs while count is less than 5. Each time, it prints the count and adds 1 to it. When count reaches 5, the condition is False and the loop stops.

âš ī¸ Important: Make sure your while loop has a way to stop! If the condition never becomes False, you'll have an infinite loop that runs forever.

FOR vs WHILE: When to Use Which?

🔁

Use FOR Loop When:

  • You know how many times to repeat
  • You're working with a list of items
  • You want to count something
# Example: Blink LED 5 times for i in range(5): GPIO.output(18, GPIO.HIGH) time.sleep(0.5) GPIO.output(18, GPIO.LOW) time.sleep(0.5)
â™žī¸

Use WHILE Loop When:

  • You don't know how many times to repeat
  • You want to keep going until something happens
  • You're waiting for a condition to change
# Example: Keep blinking until button pressed while button_not_pressed: GPIO.output(18, GPIO.HIGH) time.sleep(0.5) GPIO.output(18, GPIO.LOW) time.sleep(0.5)

Nested Loops

You can put loops inside other loops! This is called "nested loops" and it's useful for creating patterns.

Nested Loop Example

for row in range(3): for col in range(3): print("Row", row, "Column", col) print("---")

What happens: The outer loop runs 3 times. Each time, the inner loop runs 3 times. So you get 9 total prints (3 × 3).

Project: Blinking Pattern Generator

Let's create an LED that blinks in different patterns using loops!

Materials Needed:

  • Raspberry Pi
  • LED (any color)
  • Resistor (220Ί)
  • Breadboard and jumper wires

Pattern 1: Blink 5 Times

import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) # Blink 5 times for i in range(5): GPIO.output(18, GPIO.HIGH) time.sleep(0.3) GPIO.output(18, GPIO.LOW) time.sleep(0.3) GPIO.cleanup()

Pattern 2: SOS Pattern (3 short, 3 long, 3 short)

import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) # SOS pattern: ... --- ... # 3 short blinks for i in range(3): GPIO.output(18, GPIO.HIGH) time.sleep(0.2) GPIO.output(18, GPIO.LOW) time.sleep(0.2) time.sleep(0.5) # Pause between groups # 3 long blinks for i in range(3): GPIO.output(18, GPIO.HIGH) time.sleep(0.6) GPIO.output(18, GPIO.LOW) time.sleep(0.2) time.sleep(0.5) # Pause between groups # 3 short blinks again for i in range(3): GPIO.output(18, GPIO.HIGH) time.sleep(0.2) GPIO.output(18, GPIO.LOW) time.sleep(0.2) GPIO.cleanup()

Pattern 3: Fade In and Out (using while loop)

import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setup(18, GPIO.OUT) # Create PWM (Pulse Width Modulation) for fading pwm = GPIO.PWM(18, 100) # 100 Hz frequency pwm.start(0) # Start with 0% brightness # Fade in brightness = 0 while brightness <= 100: pwm.ChangeDutyCycle(brightness) time.sleep(0.05) brightness = brightness + 5 # Fade out while brightness >= 0: pwm.ChangeDutyCycle(brightness) time.sleep(0.05) brightness = brightness - 5 pwm.stop() GPIO.cleanup()

Note: This uses PWM (Pulse Width Modulation) to control LED brightness. We'll learn more about PWM in later lessons!

Loop Control: break and continue

Sometimes you want to stop a loop early or skip an iteration. Python has two special keywords for this:

âšī¸

break

Stops the loop immediately

for i in range(10): if i == 5: break # Stop at 5 print(i) # Output: 0, 1, 2, 3, 4
â­ī¸

continue

Skips the rest of this iteration

for i in range(5): if i == 2: continue # Skip 2 print(i) # Output: 0, 1, 3, 4

Common Mistakes to Avoid

âš ī¸ Watch Out For:

  • Infinite Loops: Make sure your while loop has a way to stop
  • Missing Colon: Don't forget the colon (:) after for and while
  • Wrong Indentation: Code inside loops must be indented
  • Off-by-One Errors: Remember range(5) gives 0-4, not 1-5
  • Forgetting to Update: In while loops, make sure you change the condition variable

Summary

You've learned:

  • ✅ Loops let you repeat code without writing it multiple times
  • ✅ for loops repeat a specific number of times
  • ✅ while loops repeat as long as a condition is True
  • ✅ range() creates sequences of numbers for loops
  • ✅ You can nest loops inside other loops for complex patterns
  • ✅ break stops a loop early, continue skips an iteration
  • ✅ Loops are essential for creating LED patterns and animations
🎉 Excellent Progress! You've learned how to make programs repeat actions. In the next lesson, you'll learn about functions to organize your code better!

🎮 Try It: Practice with Loops!

Practice writing loops. Try these challenges:

📝 Challenge 1: Count to 10

Write a for loop that prints numbers from 1 to 10:

📝 Challenge 2: Countdown

Write a loop that counts down from 10 to 1, then prints "Blast off!":

📝 Challenge 3: Sum Numbers

Write a loop that adds numbers from 1 to 5 and prints the total:

💡 Tip: Remember that range(5) gives 0-4, but range(1, 6) gives 1-5. Use the second form when you want to start from 1!

đŸŽ¯ Activity: Blinking Pattern Generator

What You'll Build:

Create an LED that blinks in different patterns using loops!

Step-by-Step Instructions:

  1. Set Up Hardware: Connect LED to GPIO 18 with resistor
  2. Pattern 1: Write code to blink the LED exactly 5 times using a for loop
  3. Pattern 2: Create a pattern: blink 3 times fast, pause, blink 3 times slow
  4. Pattern 3: Use nested loops to create a pattern (e.g., 3 groups of 2 blinks each)
  5. Test: Run each pattern and observe the LED behavior
  6. Experiment: Try changing the number of blinks and timing

Pattern Ideas:

  • ✅ SOS pattern: 3 short, 3 long, 3 short
  • ✅ Heartbeat pattern: 2 quick blinks, pause, repeat
  • ✅ Countdown pattern: 5 blinks, pause, 4 blinks, pause, etc.
  • ✅ Random pattern: Use nested loops for complex sequences
🏆 Bonus Challenge: Can you create a pattern that blinks faster and faster each time? (Hint: use a variable to change the sleep time inside the loop)

đŸ’Ē Practice Challenges

Challenge 1: Multiplication Table

Write a loop that prints the 5 times table (5 × 1 = 5, 5 × 2 = 10, etc.) up to 5 × 10:

# Example: for i in range(1, 11): result = 5 * i print("5 ×", i, "=", result)

Challenge 2: LED Blink Counter

Write code that blinks an LED 10 times, but prints the count each time:

  • Blink 1, Blink 2, Blink 3, etc.
  • After 10 blinks, print "Done!"

Challenge 3: Stop at 7

Write a loop that counts from 1 to 10, but stops (using break) when it reaches 7:

# Example: for i in range(1, 11): if i == 7: break print(i) # Output: 1, 2, 3, 4, 5, 6

Challenge 4: Skip Even Numbers

Write a loop that prints numbers 1-10, but skips even numbers (use continue):

# Example: for i in range(1, 11): if i % 2 == 0: # If number is even continue # Skip it print(i) # Output: 1, 3, 5, 7, 9

Challenge 5: Nested Loop Pattern

Use nested loops to create this pattern:

* ** *** **** *****
Click to see the answer
for row in range(1, 6): for col in range(row): print("*", end="") print() # New line after each row