Module 4: Loops and Iteration
It's time to put your program to work! In this module, you'll learn how to perform repetitive tasks efficiently using loops, one of the most fundamental concepts in programming.
1. Why We Need Loops: The DRY Principle
Imagine you needed to print the numbers from 1 to 5. Without loops, you might write:
This works, but what if you needed to print to 100? Or 1,000? Writing a line for each number would be tedious, inefficient, and prone to errors. This violates a core programming concept: the **DRY (Don't Repeat Yourself)** principle. The goal is to write a piece of logic once and reuse it.
Loops are control structures that allow you to execute a block of code repeatedly. This process of repetition is called **iteration**.
🧠 Core Concept: Automation Through Repetition
Loops are the programmer's primary tool for automation. They take a manual, repetitive task and turn it into an automated process that can scale to thousands or millions of repetitions without any extra coding effort. They are essential for processing collections of data, from lists of users to pixels in an image.
2. The `for` Loop: Iterating Over a Sequence
The `for` loop is used when you have a known sequence of items and you want to do something for each item in that sequence. Think of it as saying, "For each item in this collection, perform this action."
To create a sequence of numbers, we can use the built-in `range()` function.
The `range()` function
- `range(5)` generates numbers from 0 up to (but not including) 5. So, it produces `0, 1, 2, 3, 4`.
- `range(1, 6)` generates numbers starting from 1 up to (but not including) 6. So, it produces `1, 2, 3, 4, 5`.
Example: Printing Numbers with a `for` loop
Let's break down the syntax:
- `for`: The keyword that starts the loop.
- `number`: A temporary variable that holds the current item from the sequence in each iteration. You can name this anything you want (e.g., `i`, `item`, `num`).
- `in`: A keyword that connects the temporary variable to the sequence.
- `range(1, 6)`: The sequence we are iterating over.
- `:`: The colon that ends the line.
- The indented block of code below is the **loop body**. This is what gets executed on each iteration.
3. The `while` Loop: Repeating Based on a Condition
What if you don't know exactly how many times you need to loop? The `while` loop is used to repeat a block of code as long as a certain condition remains `True`.
A `while` loop requires three parts to function correctly:
- Initialization: A variable is set up before the loop starts.
- Condition: The loop continues as long as this evaluates to `True`.
- Update: Inside the loop, the variable is changed in a way that will eventually make the condition `False`.
Example: A Simple Countdown
This loop will print 5, 4, 3, 2, 1, and then "Blast off!" once the `countdown` variable is no longer greater than 0.
⚠️ Warning: The Infinite Loop
If you forget the "update" step in a `while` loop, the condition may never become false. This creates an **infinite loop**, where your program gets stuck repeating the same code forever and will need to be manually stopped. For example: `while True: print("Help, I'm stuck!")`.
4. Controlling the Flow: `break` and `continue`
Sometimes you need more fine-grained control over your loops. Python provides two statements to change the standard behavior of a loop: `break` and `continue`.
`break`: Exiting a Loop Early
The `break` statement immediately terminates the loop, regardless of the loop's condition. The program's execution continues at the first line of code after the loop.
Example: Finding a Target Number
This loop will print "Checking..." for numbers 1 through 7, then print "Found it!" and stop completely. It will not continue to 100.
`continue`: Skipping the Current Iteration
The `continue` statement ends the current iteration and immediately jumps to the beginning of the next one. It's useful for skipping over certain values.
Example: Printing Only Odd Numbers
This code will print 1, 3, 5, 7, and 9. When `number` is even, the `continue` statement is triggered, and the `print(number)` line is skipped for that iteration.
5. An Uncommon Feature: The `else` Block in Loops
Python loops have a unique feature that many other languages don't: an optional `else` block. The code in the `else` block is executed only if the loop completes its entire sequence **without** being terminated by a `break` statement.
Example: Searching for an item
This is a very clean way to handle a "search and report" scenario. If the item is found, the loop breaks, and the `else` block is skipped. If the loop finishes naturally (meaning the item was never found), the `else` block runs.
You've Completed Module 4!
Congratulations on mastering loops! You now know how to automate repetitive tasks, which is a superpower in programming. You can iterate through sequences with `for` loops and repeat actions based on conditions with `while` loops.
In the next module, we'll learn how to organize our code into reusable blocks called functions.
On to Module 5: Functions and Modules →