For Loops + Range

For Loops

For loops keep doing something for a "known" number of times. This is similar to while loops. In fact, the usages of for loops and while loops overlap in some cases.

<aside> 💡 Similar to if statements, while and for loops must be indented in order for them to work properly

</aside>

Range

Let's first introduce range(). range() takes an integer x and keeps spitting out numbers from 0 to x-1 in order. This has 2 uses:

  1. we can use these numbers like printing them
  2. we can take advantage of the fact that range(x) spits out numbers x times to perform operations x times. For example
# stop
for i in range(5):
	print(i)

Notice how 0 to 4 are printed on 5 separate lines. This indicates that print was run 5 separate times, and the number printed was from the range 0 to x-1. In programming terms, we say that it printed the numbers 0-5, exclusive, since 5 was not included

<aside> 💡 i is just a name for a variable. You can replace it with anything (that follows Python variable naming rules) to make your code more readable

</aside>

range() also can take the starting point. Before, we put in one value for range() and that indicated the endpoint (exclusive). The starting point by default was 0. Now range(x, y) means x is the starting point, and y is the ending point (exclusive). For example:

# start, stop
for i in range(1, 5):
	print(i)

Notice how 1 to 4 were printed on 4 separate lines

range(x, y, z): if three numbers are put into the range function, the first two are the same as before and the third one represents the interval of increase (also called the 'step') between each number outputted. The step is 1 by default. For example:

# start, stop, step
for i in range(2, 5, 2):
	print(i)

Notice how 2 and 4 were printed on 2 separate lines.