Skip to main content

๐Ÿ” Lesson 6: Loops โ€” Making Python Repeat Tasks

Imagine having to write "I will not throw paper airplanes" 100 times on the blackboard. Would you rather write it 100 times, or tell the computer to repeat it for you? That's the power of loops!

๐ŸŽฏ Learning Objectives

By the end of this lesson, you will be able to:

  • Use for loops with range() to repeat code a specific number of times
  • Iterate through strings and lists with for loops
  • Use while loops for condition-based repetition
  • Control loops with break and continue
  • Build nested loops for complex patterns

Estimated Time: 50โ€“65 minutes

Project: Build a number guessing game and ASCII art patterns using loops

In This Lesson

๐Ÿ’ก Why Loops?

# Without loops (the painful way):
print("I will not throw paper airplanes")
print("I will not throw paper airplanes")
print("I will not throw paper airplanes")
# ... 97 more times?! No thanks!

# With loops (the smart way):
for i in range(100):
    print("I will not throw paper airplanes")

๐Ÿ”ข The For Loop โ€” Counting Made Easy

A for loop is like a reliable friend who counts for you:

๐Ÿ”„ How a For Loop Works 0 1 2 โ† currently here 3 4 for i in range(5): print(i) Output: 0 1 2 3 4
Figure 1: A for loop walks through each value one at a time, from start to end.

๐Ÿ“ Understanding range()

The range() function is like a number generator:

# range(stop) - counts from 0 to stop-1
for i in range(5):
    print(i)  # Prints: 0, 1, 2, 3, 4

# range(start, stop) - counts from start to stop-1
for i in range(2, 7):
    print(i)  # Prints: 2, 3, 4, 5, 6

# range(start, stop, step) - counts by step
for i in range(0, 10, 2):
    print(i)  # Prints: 0, 2, 4, 6, 8

# Counting backwards
for i in range(10, 0, -1):
    print(i)  # Prints: 10, 9, 8, 7, 6, 5, 4, 3, 2, 1
print("Blast off! ๐Ÿš€")
Syntax Produces Use Case
range(5)0, 1, 2, 3, 4Simple counting from 0
range(2, 7)2, 3, 4, 5, 6Start from a specific number
range(0, 10, 2)0, 2, 4, 6, 8Skip/step counting
range(10, 0, -1)10, 9, 8, โ€ฆ 1Counting backwards

๐Ÿ”ค Looping Through Strings and Lists

For loops can walk through text letter by letter, or through lists item by item:

# Looping through a string
name = "Python"
for letter in name:
    print(f"Give me a {letter}!")
print("What does that spell? PYTHON!")

# Looping through a list
fruits = ["apple", "banana", "cherry", "date"]
for fruit in fruits:
    print(f"I like {fruit}s")

# With index numbers
for i in range(len(fruits)):
    print(f"{i+1}. {fruits[i]}")

๐Ÿ†• Advanced: enumerate() and zip()

Python provides powerful functions to enhance your loops:

# enumerate() - get both index and value
fruits = ["apple", "banana", "cherry"]

# The Pythonic way
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")

# Start counting from 1 instead of 0
for number, fruit in enumerate(fruits, start=1):
    print(f"{number}. {fruit}")

# zip() - loop through multiple lists together
names = ["Alice", "Bob", "Carol"]
ages = [25, 30, 28]

for name, age in zip(names, ages):
    print(f"{name} is {age} years old")

โณ The While Loop โ€” Keep Going Untilโ€ฆ

While loops are like saying "keep doing this as long as something is true":

graph TD A["๐Ÿš€ Start"] --> B{"๐Ÿ” Condition True?"} B -->|"Yes โœ…"| C["โš™๏ธ Do something"] C --> D["๐Ÿ”„ Update condition"] D --> B B -->|"No โŒ"| E["๐Ÿ Exit loop"] E --> F["โ–ถ๏ธ Continue program"]
# Basic while loop
countdown = 5
while countdown > 0:
    print(f"{countdown}...")
    countdown = countdown - 1  # or countdown -= 1
print("Happy New Year! ๐ŸŽ‰")

# User-controlled loop
password = ""
while password != "secret":
    password = input("Enter password: ")
    if password != "secret":
        print("Wrong! Try again.")
print("Access granted!")

๐ŸŽฎ Interactive Example: Guessing Game

Let's build a fun number guessing game using loops:

import random

# Computer picks a random number
secret_number = random.randint(1, 100)
guesses = 0
found = False

print("I'm thinking of a number between 1 and 100!")
print("Can you guess it?")

while not found:
    guess = int(input("Your guess: "))
    guesses += 1

    if guess < secret_number:
        print("Too low! Try higher.")
    elif guess > secret_number:
        print("Too high! Try lower.")
    else:
        found = True
        print(f"๐ŸŽ‰ Correct! You got it in {guesses} tries!")

        if guesses <= 5:
            print("Amazing! You're a mind reader!")
        elif guesses <= 10:
            print("Great job!")
        else:
            print("Keep practicing!")

โฑ๏ธ When to Use Which Loop?

# Use FOR loops when:
# - You know the number of iterations
for i in range(100):
    process_item(i)

# - Iterating through collections
for item in my_list:
    print(item)

# Use WHILE loops when:
# - Condition-based repetition
while user_input != "quit":
    user_input = input("Enter command: ")

# - Unknown number of iterations
while not found:
    keep_searching()

๐Ÿšฆ Break and Continue

Sometimes you need an emergency exit from a loop, or want to skip certain steps:

break Exits the loop completely ๐Ÿšช Like: "I'm done!" Output: 0 1 2 continue Skips to next iteration โญ๏ธ Like: "Skip this one" Output: 0 1 2 4 for i in range(5): if i == 3: break print(i) for i in range(5): if i == 3: continue print(i)
Figure 2: break exits the loop entirely; continue skips just the current step.
# Using break - exit when found
items = ["sock", "shoe", "keys", "wallet", "phone"]
print("Looking for my keys...")

for item in items:
    print(f"Found: {item}")
    if item == "keys":
        print("Got them! No need to keep looking.")
        break

# Using continue - skip certain items
print("\nCounting to 10, but 7 is unlucky:")
for i in range(1, 11):
    if i == 7:
        continue  # Skip 7
    print(i, end=" ")  # end=" " keeps numbers on same line

๐Ÿ†˜ Infinite Loop Recovery

Got stuck in an infinite loop? Here's how to escape:

  • In IDLE / Terminal: Press Ctrl+C
  • In Jupyter / Colab: Interrupt kernel button
  • Last Resort: Close the terminal window

๐Ÿช† Nested Loops and Patterns

You can put loops inside loops, like a clock (hours loop contains minutes loop):

# Drawing a rectangle with stars
width = 5
height = 3

for row in range(height):
    for col in range(width):
        print("*", end=" ")
    print()  # New line after each row

# Output:
# * * * * *
# * * * * *
# * * * * *

# Multiplication table
print("\nMultiplication Table:")
for i in range(1, 6):
    for j in range(1, 6):
        print(f"{i*j:3}", end=" ")  # :3 makes numbers align
    print()

๐ŸŽจ Fun Project: ASCII Art Patterns

# Triangle pattern
print("Triangle:")
for i in range(1, 6):
    print("*" * i)

# Pyramid pattern
print("\nPyramid:")
for i in range(1, 6):
    spaces = " " * (5 - i)
    stars = "*" * (2 * i - 1)
    print(spaces + stars)

# Diamond pattern
print("\nDiamond:")
for i in range(1, 5):
    spaces = " " * (4 - i)
    stars = "*" * (2 * i - 1)
    print(spaces + stars)
for i in range(3, 0, -1):
    spaces = " " * (4 - i)
    stars = "*" * (2 * i - 1)
    print(spaces + stars)

Output:

Triangle:
*
**
***
****
*****

Pyramid:
    *
   ***
  *****
 *******
*********

๐Ÿš€ Preview: List Comprehensions

Python offers a concise way to create lists using loops:

# Traditional loop approach
squares = []
for i in range(10):
    squares.append(i ** 2)

# List comprehension (same result, one line!)
squares = [i ** 2 for i in range(10)]

# With conditions
evens = [x for x in range(20) if x % 2 == 0]

# Practical example: Convert temperatures
celsius = [0, 10, 20, 30, 40]
fahrenheit = [(c * 9/5) + 32 for c in celsius]

๐Ÿงฉ Common Loop Patterns

# Pattern 1: Accumulator (building up a result)
total = 0
for i in range(1, 11):
    total += i
print(f"Sum of 1-10: {total}")

# Pattern 2: Finding maximum/minimum
numbers = [45, 22, 88, 13, 99, 31]
highest = numbers[0]  # Start with first number
for num in numbers:
    if num > highest:
        highest = num
print(f"Highest number: {highest}")

# Pattern 3: Counting occurrences
text = "mississippi"
count = 0
for letter in text:
    if letter == "s":
        count += 1
print(f"The letter 's' appears {count} times")

# Pattern 4: Input validation
while True:
    age = input("Enter your age (0-150): ")
    if age.isdigit() and 0 <= int(age) <= 150:
        age = int(age)
        break
    print("Invalid age! Try again.")
print(f"Your age is {age}")
graph TD A["๐Ÿงฉ Common Loop Patterns"] --> B["โž• Accumulator"] A --> C["๐Ÿ† Find Max/Min"] A --> D["๐Ÿ”ข Count Occurrences"] A --> E["โœ… Input Validation"] B --> F["Sum, concat, build list"] C --> G["Track best value so far"] D --> H["Count matches in data"] E --> I["Repeat until valid input"]

๐Ÿ› Common Mistakes to Avoid

โš ๏ธ Infinite Loops โ€” The Never-ending Story

# Wrong - this will run forever!
x = 1
while x > 0:
    print(x)
    # Forgot to change x!

# Right - always update the condition
x = 10
while x > 0:
    print(x)
    x -= 1  # This ensures loop will end

โš ๏ธ Off-by-one Errors

# Common mistake - range stops BEFORE the end
for i in range(10):
    print(i)  # Prints 0-9, not 1-10!

# If you want 1-10:
for i in range(1, 11):
    print(i)

โœ… Loop Wisdom

"The computer is incredibly fast, accurate, and stupid. The human is incredibly slow, inaccurate, and brilliant. Together they are powerful beyond imagination." โ€” Use loops to let the computer do what it does best: repeat tasks quickly and accurately!

๐Ÿ‹๏ธ Practice Exercises

๐Ÿ‹๏ธ Exercise 1: Countdown Timer

Objective: Create a countdown using a while loop.

Instructions:

  1. Ask user for a number of seconds
  2. Count down to zero
  3. Show "Time's up!" with a fun message
  4. Bonus: Add time.sleep(1) to pause between counts
๐Ÿ’ก Hint

Use import time at the top, then time.sleep(1) inside the loop to wait 1 second between each count.

โœ… Solution
import time

seconds = int(input("Enter countdown seconds: "))

while seconds > 0:
    print(f"โฑ๏ธ {seconds}...")
    time.sleep(1)
    seconds -= 1

print("๐ŸŽ‰ Time's up! Ding ding ding!")

๐Ÿ‹๏ธ Exercise 2: Password Strength Checker

Objective: Use loops to analyze password strength.

Instructions:

  1. Take a password input
  2. Use loops to check for: length (8+ characters), contains numbers, contains uppercase letters, contains special characters
  3. Give a strength score
๐Ÿ’ก Hint

Loop through each character and use .isdigit(), .isupper(), and check if it's in a string of special characters like "!@#$%^&*".

โœ… Solution
password = input("Enter a password to check: ")

has_number = False
has_upper = False
has_special = False
specials = "!@#$%^&*()-_=+[]{}|;:',.<>?/"

for char in password:
    if char.isdigit():
        has_number = True
    elif char.isupper():
        has_upper = True
    elif char in specials:
        has_special = True

score = 0
if len(password) >= 8:
    score += 1
if has_number:
    score += 1
if has_upper:
    score += 1
if has_special:
    score += 1

print(f"\nPassword Strength: {score}/4")
if score <= 1:
    print("๐Ÿ”ด Weak โ€” add more variety!")
elif score <= 2:
    print("๐ŸŸก Fair โ€” getting better")
elif score <= 3:
    print("๐ŸŸข Strong โ€” nice work!")
else:
    print("๐Ÿ’ช Very Strong โ€” excellent!")

๐Ÿ‹๏ธ Exercise 3: Shopping List Manager

Objective: Build an interactive loop-driven program.

Instructions:

  1. Let users add items to a list
  2. Show the current list
  3. Let users remove items
  4. Continue until user types "done"
๐Ÿ’ก Hint

Use a while True loop with break when the user types "done". Use .append() to add and .remove() to delete items.

โœ… Solution
shopping_list = []

while True:
    print(f"\n๐Ÿ“ List ({len(shopping_list)} items): {shopping_list}")
    action = input("(a)dd, (r)emove, or (d)one? ").lower()

    if action == "d":
        break
    elif action == "a":
        item = input("Item to add: ")
        shopping_list.append(item)
        print(f"โœ… Added '{item}'")
    elif action == "r":
        item = input("Item to remove: ")
        if item in shopping_list:
            shopping_list.remove(item)
            print(f"โŒ Removed '{item}'")
        else:
            print(f"'{item}' not in list!")

print(f"\nFinal list: {shopping_list}")

๐ŸŽฏ Quick Quiz

Question 1: What does range(3, 8) produce?

Question 2: What does break do inside a loop?

Question 3: Which loop type is best when you don't know how many times to repeat?

Summary

๐ŸŽ‰ Key Takeaways

  • Loops let you repeat code without copy-pasting
  • for loops are great when you know how many times to repeat
  • while loops are perfect when you repeat until a condition is met
  • break exits a loop early, continue skips to next iteration
  • You can nest loops inside each other
  • Always ensure while loops can end (avoid infinite loops!)

๐Ÿ“Œ Real-World Applications

Loops are everywhere: data processing (loop through thousands of records), games (game loop that runs until game over), animations (repeat drawing frames), servers (keep listening for requests), and automation (repeat tasks like file backups).

๐Ÿš€ What's Next?

Now that you can make Python repeat tasks, we'll learn about lists โ€” how to store and organize multiple pieces of data. Think of it as giving Python a better memory!

๐ŸŽ‰ Congratulations!

You've completed Module 3: Control Flow! You can now make Python decide and repeat. These are two of the most fundamental skills in all of programming. Onward to data structures!