๐Ÿ”ข 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.

Free ยท US Letter ยท no sign-up
Google Classroom Save to Pinterest Email me

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 * i each time.

๐Ÿ“Œ Remember: for = โ€œfor each one of โ€ฆโ€ โ€” a known number of repeats.

Quick quiz

  1. What does for i in range(5): print(i) show?

  2. What else can a for loop go through?

  3. What does range(1, 6) give?

๐Ÿ”Ž Ask Thinkapedia another question