For loop with range - Learn Python 3 - Snakify

Lesson 4. For loop with range

1. For loop with range

In the previous lessons we dealt with sequential programs and conditions. Often the program needs to repeat some block several times. That's where the loops come in handy. There are for and while loop operators in Python, in this lesson we cover for.

for loop iterates over any sequence. For instance, any string in Python is a sequence of its characters, so we can iterate over them using for:

for character in 'hello':

Another use case for a for-loop is to iterate some integer variable in increasing or decreasing order. Such a sequence of integer can be created using the function range(min_value, max_value):

for i in range(5, 8):
    print(i, i ** 2)
print('end of loop')
# 5 25
# 6 36
# 7 49
# end of loop

Function range(min_value, max_value) generates a sequence with numbers min_value, min_value + 1, ..., max_value - 1. The last number is not included.

There's a reduced form of range() - range(max_value), in which case min_value is implicitly set to zero:

for i in range(3):
# 0
# 1
# 2

This way we can repeat some action several times:

for i in range(2 ** 2):
    print('Hello, world!')

Same as with if-else, indentation is what specifies which instructions are controlled by for and which aren't.

Range() can define an empty sequence, like range(-5) or range(7, 3). In this case the for-block won't be executed:

for i in range(-5):
    print('Hello, world!')

Let's have more complex example and sum the integers from 1 to n inclusively.

result = 0
n = 5
for i in range(1, n + 1):
    result += i
    # this ^^ is the shorthand for
    # result = result + i

Pay attention that maximum value in range() is n + 1 to make i equal to n on the last step.

To iterate over a decreasing sequence, we can use an extended form of range() with three arguments - range(start_value, end_value, step). When omitted, the step is implicitly equal to 1. However, can be any non-zero value. The loop always includes start_value and excludes end_value during iteration:

for i in range(10, 0, -2):
# 10
# 8
# 6
# 4
# 2

2. setting the function print()

By default, the function print() prints all its arguments separating them by a space and the puts a newline symbol after it. This behavior can be changed using keyword arguments sep (separator) and end.
print(1, 2, 3)
print(4, 5, 6)
print(1, 2, 3, sep=', ', end='. ')
print(4, 5, 6, sep=', ', end='. ')
print(1, 2, 3, sep='', end=' -- ')
print(4, 5, 6, sep=' * ', end='.')