๐ข For Loop
5th Grade ๐ป Coding
A for loop is a loop that repeats a known number of times, or goes one by one through every item in a list.
In Python, for i in range(5): print(i) shows the numbers 0 through 4 โ five repeats. range creates a series of numbers that starts at 0 and stops just before the number in the parentheses. range(1, 6) gives 1 through 5.
A for loop can also go through a list: for f in fruits: print(f) shows each fruit in the list, one per line. On each repeat, the variable f gets the next item. This is one of the most common ways to use loops โ doing something to every item in a collection.
For example
- For every student on the class list, print a certificate: a for loop over a list of names.
- To print the 7 times table, you write a loop over the numbers 1 through 10 and show
7 * ieach time.
๐ Remember: for = โfor each one of โฆโ โ a known number of repeats.
Quick quiz
What does for i in range(5): print(i) show?
What else can a for loop go through?
What does range(1, 6) give?