๐ 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
forloops withrange()to repeat code a specific number of times - Iterate through strings and lists with for loops
- Use
whileloops for condition-based repetition - Control loops with
breakandcontinue - 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:
๐ 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, 4 | Simple counting from 0 |
range(2, 7) | 2, 3, 4, 5, 6 | Start from a specific number |
range(0, 10, 2) | 0, 2, 4, 6, 8 | Skip/step counting |
range(10, 0, -1) | 10, 9, 8, โฆ 1 | Counting 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":
# 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 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}")
๐ 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:
- Ask user for a number of seconds
- Count down to zero
- Show "Time's up!" with a fun message
- 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:
- Take a password input
- Use loops to check for: length (8+ characters), contains numbers, contains uppercase letters, contains special characters
- 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:
- Let users add items to a list
- Show the current list
- Let users remove items
- 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
forloops are great when you know how many times to repeatwhileloops are perfect when you repeat until a condition is metbreakexits a loop early,continueskips 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!