For loops & ranges
Now we'll learn a more specialized loop: the for
loop. The uses of a for
loop vary by language, but in Python, a for
loop is useful whenever we want to iterate through a sequence, like iterating through a range of numbers or through a list of items.
Here's the general template of a for
loop:
for in :
The loop below iterates through a sequence of numbers, printing their multiples of 9. Try it!
for num in range(1, 5):
print(9 * num)
Writing that same program with a while
loop would require additional lines of code :
num = 1
while num < 5:
print(9 * num)
num += 1
As you can see, a for
loop can be a much more concise way of writing a loop than a while
loop. When it's possible to use a for
loop, it's generally the preferred way, and while
loops can be reserved for more exotic computations.
Now let's dig into how range()
works.
Ranges
The example above iterated through the numbers 1 through 4 by calling range()
, a function that constructs a sequence of numbers. The range()
function can be called with a varying number of arguments, and behaves differently depending on how many arguments it's called with.
If range()
is called with just one argument, then the range starts at 0 and ends just before the given value.
For example, this code prints the numbers 0 through 5 (not including 6):
for num in range(6):
print(num)
If range()
is called with two arguments, then the range starts at the first value and ends just before the second value.
For example, this code prints the numbers 1 through 5:
for num in range(1, 6):
print(num)
Finally, if range()
is called with three arguments, then the range will increment according to the third value.
The example below prints the numbers 1, 3, and 5, since the range increments by 2 instead of 1 (the default):
for num in range(1, 6, 2):
print(num)