What Is a Loop?
Imagine you need to print the numbers 1 through 100. Without loops, you'd write 100 separate print statements. That's tedious, error-prone, and inflexible — what if you later need 1 to 1000? Loops solve this problem by letting you repeat code automatically.
A loop executes a block of code multiple times. You write the instructions once, and the loop handles the repetition. This is one of the most powerful concepts in programming.
Why Loops Exist
Loops exist because programs constantly need to do the same thing to multiple items:
- Send an email to every subscriber
- Check each item in a shopping cart
- Process every row in a spreadsheet
- Validate each field in a form
Without loops, these tasks would require copying and pasting code for each item — impractical and unmaintainable.
Two Types of Loops
Python offers two main loop types:
For loops iterate over a sequence of items. "For each name in this list, print a greeting." You know (or can calculate) how many times the loop will run.
While loops repeat as long as a condition is true. "While the user hasn't typed 'quit', keep asking for input." You might not know in advance how many iterations will occur.
Both achieve repetition, but they're suited to different situations.
The Assembly Line Analogy
Think of a factory assembly line. Each station performs the same operation on every product that passes through. The worker doesn't need separate instructions for each product — they have one set of instructions that applies to all items.
Your loop is like that assembly line. The code inside the loop is the operation, and each iteration processes a different item.
What You'll Learn Next
In the following lessons, you'll learn the specific syntax for for loops and while loops. You'll see how to iterate over lists, count through ranges of numbers, and repeat until conditions change. These patterns appear in virtually every program you'll write.