for Loops
beginner10 min readLesson 20 of 169
Walk collections with for โ and the rules of the loop block.
Loops repeat work โ the difference between typing 100 print statements and one.
for: walk a collection
fruits = ["apple", "pear", "plum"]
for fruit in fruits:
print(f"today: {fruit}")
Read it as a sentence: "for each fruit in fruits, do the indented
block". The loop variable (fruit) takes each value in turn. Note: fruit
sensibly singular vs fruits plural โ name loop variables like you mean it.
Strings are walkable too
for ch in "abc":
print(ch) # a, b, c
Indentation again
The indented block runs once per item. Dedent to run after the loop:
for fruit in fruits:
print(fruit)
print("done") # runs once, after all fruit