for loops, explained simply
Imagine planting ten flowers by writing the same line ten times. It works, but it is slow and easy to get wrong. A loop lets you write the instruction once and tell Python how many times to repeat it.
A for loop starts with for, then a variable name, then in, then something to go through, and ends with a colon. The lines that should repeat are indented underneath, usually by four spaces.
Each time round the loop, the variable holds the next value. With range(5) that means 0, 1, 2, 3 and 4, which is five repeats in total.
Example: Plant a row of flowers
for flower in range(4):
print("Plant a flower")
print("The garden is ready!")Output
Plant a flower
Plant a flower
Plant a flower
Plant a flower
The garden is ready!The last line is not indented, so it runs once, after the loop has finished.
Try this
- Change 4 to 10 and watch the garden grow.
- Print the loop variable itself inside the loop to see the numbers it counts through.
- Indent the last line too and notice how the output changes.
