Chapters List
- A Mental Model for Programming
- What Happens When a Program Runs
- Programming Languages
- Variables and Data
- Decisions: Conditional Logic
- Repetition: Loops
- Functions: Building Reusable Code
- Data Structures: Organizing Information
- Debugging: Fixing Programs
- How Programs Become Real Software
- Different Types of Programming
- Modern Programming and Software Development
programming
Repetition: Loops
Learn how loops let programs repeat work efficiently across large amounts of data.
In the previous chapter we learned how programs make decisions.
Another major need is repetition.
Many tasks are not one-time actions. They involve doing the same step many times.
Why Loops Exist
Imagine processing 10,000 log entries.
Writing 10,000 manual statements is impossible.
Loops allow one block of logic to run repeatedly.
This is a core reason programming scales.
Iteration in Practice
Common repetitive tasks include:
- counting from 1 to N
- scanning a list of files
- summing transaction amounts
- validating many user records
A loop turns these from manual work into automated workflows.
Two Common Loop Styles
While Loop
Runs while a condition remains true.
count = 0
while count < 5:
print(count)
count = count + 1
For Loop
Iterates over items in a sequence.
numbers = [2, 4, 6]
for n in numbers:
print(n)
Loop Flow
graph TD
A[Start Loop] --> B{Condition True?}
B -->|Yes| C[Run Body]
C --> D[Update State]
D --> B
B -->|No| E[Exit Loop]
The update step is critical. Without it, loops can run forever.
Processing Collections
Loops are especially useful with lists of data.
Example:
total = 0
prices = [10, 25, 15]
for price in prices:
total = total + price
This pattern appears in analytics, file processing, web backends, and system automation.
Infinite Loops and Safety
A loop that never terminates is an infinite loop.
Sometimes infinite loops are intentional (for example, long-running servers).
But in beginner programs, they are usually bugs caused by missing state updates or incorrect conditions.
Key Ideas to Remember
- Loops automate repeated work.
whileloops are condition-driven.forloops are collection-driven.- Loop correctness depends on valid condition + state updates.
- Iteration is essential for working with large datasets.
What Comes Next
Loops help us repeat logic.
Next we need a way to organize and reuse logic cleanly:
functions, the building blocks of structured programs.