Sub topic 1
What a for Loop Can Iterate Over
Prerequisites
Assume you know Python variables, indentation, print(), lists, strings, integers, and how to run a Python 3 script.
What a `for` Loop Can Iterate Over
A for loop processes the items in an iterable, an object that can provide its values one at a time. Lists, strings, tuples, dictionaries, sets, and ranges are common iterables.
A list provides its elements. A string provides its characters. A dictionary provides its keys unless you explicitly request its values or key-value pairs.
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
for character in "Python":
print(character)
prices = {"tea": 3, "cake": 5}
for item, price in prices.items():
print(item, price)The `for` Statement
A for statement assigns each item to a loop variable and runs the indented body. The body runs once for every item. When no items remain, the loop ends.
flowchart TD
A[Get next item] --> B[Assign it to loop variable]
B --> C[Run indented body]
C --> A
A --> D[No items remain]Counting with `range()`: start, stop, step
Use range() when you need a sequence of integers. Its stop value is excluded.
range(stop)starts at0.range(start, stop)starts atstart.range(start, stop, step)changes bystep.
print(list(range(5))) # [0, 1, 2, 3, 4]
print(list(range(2, 8))) # [2, 3, 4, 5, 6, 7]
print(list(range(0, 10, 3))) # [0, 3, 6, 9]range() returns a range object rather than a list. It represents the sequence without storing every value, which is useful for large counts.
Stepping and Counting Backwards
A positive step counts upward. A negative step counts downward. For a negative step, start must be greater than stop, or the range is empty.
for number in range(5, 0, -1):
print(number)This prints 5 through 1, not 0, because the stop value is always excluded.
Exercise
What does list(range(1, 8, 2)) produce?
Show answer
[1, 3, 5, 7].