Home › Learn › Python › Loops

for loops and range

Lesson 11 of 40. Repeat a block for each number in a range.

for i in range(5): runs the block five times with i taking the values 0, 1, 2, 3, 4. range(start, stop) counts from start up to but not including stop; range(start, stop, step) jumps by step, and a negative step counts down. The stop value being excluded is the thing everyone trips on once: range(1, 11) is one to ten.

A loop often builds up a result in a variable created before the loop: start total = 0, add to it inside, use it after. total += x is shorthand for total = total + x.

for walks any sequence, not only a range: for ch in text: visits each character of a string in turn, and ch in "aeiou" asks whether that character is one of those five. That is how you count or inspect letters.

total = 0
for n in range(1, 4):
    total += n
print(total)   # 6

for n in range(10, 0, -3):
    print(n)   # 10, 7, 4, 1

Your task

Write sum_to(n) that returns 1 + 2 + ... + n using a loop (return 0 for n of 0), count_down(n) that returns the list [n, n-1, ..., 1], so count_down(3) is [3, 2, 1], and count_vowels(text) that returns how many characters of the text are vowels (a, e, i, o, u, in either case).

Part of the final project. count_vowels counts the vowels in the raw text for one line of the report. It is saved in this browser and loaded into Project: text statistics when you get there.

Hint 1

range(1, n + 1) includes n. Counting down: for i in range(n, 0, -1): result.append(i)

Hint 2

for ch in text.lower(): if ch in "aeiou": total += 1

Show the solution
def sum_to(n):
    total = 0
    for i in range(1, n + 1):
        total += i
    return total


def count_down(n):
    result = []
    for i in range(n, 0, -1):
        result.append(i)
    return result


def count_vowels(text):
    total = 0
    for ch in text.lower():
        if ch in "aeiou":
            total += 1
    return total

    Runs CPython compiled to WebAssembly in this tab (12 MB download the first time, then cached); nothing is sent anywhere.