Definition
A control flow statement used to iterate over a sequence (such as a list, tuple, or range) and execute a block of code for each item in that sequence.
Why It Matters
The for loop is the foundational engine of algorithmic scaling; it allows a single programmer to perform work on millions of data points simultaneously, transforming coding from manual data entry into the construction of automated labor systems.
Core Concepts
- Iteration: The process of repeating an action for every element in a set.
- The range() Function:
range(stop): Iterates from 0 up to (but not including)stop.range(start, stop): Iterates fromstartup to (but not including)stop.range(start, stop, step): Iterates using a specific increment.- Negative Step: Using a negative
step(e.g.,range(5, -1, -1)) allows for counting down.
- Indentation: Python uses whitespace to define the “scope” of the loop. Code intended to repeat must be indented.
- Example Usage:
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(f"I like {fruit}s")
# Using range() for numerical iteration
for i in range(1, 4):
print(f"Attempt #{i}")
- Loop Control:
breakandcontinuefunction identically to their use inwhileloops.