0%

Repeating Work with Loops · practice

Count with range()

So far, every for has walked through something that already existed, such as a or a . Sometimes there is no collection to process. You simply want a sequence of numbers.

Python’s range() produces whole numbers for a loop to walk through:

Try it

The loop prints five numbers: 0, 1, 2, 3, and 4.

Start at zero and stop before the end

With one , range(5) means “produce five numbers, starting at zero.” The argument is the stop . Counting ends before that value, so 5 is not included.

You have seen the same stop rule in string and list : the start is included and the stop is left out. This makes the number of produced values predictable.

Choose where counting starts

Give range() two arguments when counting should start somewhere other than zero:

Try it

The first argument is the start, and the second is the stop. The start is included, so the first year is 2021. The stop is excluded, so the final year is 2024.

You can read range(2021, 2025) as “start at 2021 and continue while the number is still below 2025.”

Which numbers does range(2, 6) produce?

Collect a simple range

The editor contains an empty numbers list. Loop over range(count) and append every produced number so you can see exactly where the starts and stops.

Task

Complete the program.

  • over range(count) with number as the loop .

  • Append each number to numbers.

  • Keep the final print(numbers) line.

With count = 6, the result should contain six numbers starting at zero. Do not write the numbers into the by hand.