smartyfy.mrindigi.com

Python Master Course V2 — 024. Range and Numeric Iteration

SMARTYFY ACADEMY · MODULE 03 · LESSON 024 OF 200

Range and Numeric Iteration

Estimated study: 60–90 minutes · Prerequisite: Lesson 023 and preceding Python foundations.

Use range with start stop and step without off-by-one errors.

Video lesson

Video not available yet. This position is reserved for a verified lesson video link or player. The written lesson can be completed without it.

Learning outcomes

  • Explain use range with start stop and step without off-by-one errors.
  • Trace program state and predict the output.
  • Recognize common errors and boundary conditions.
  • Apply the concept to a complete practical project.
  • Write independent tests and justify results.

Understand the technique

A range describes a sequence of integers

Use range() when repetition depends on integer positions or a known number of steps. Three forms cover the common cases: range(stop) starts at zero and steps by one; range(start, stop) uses your starting value and still steps by one; range(start, stop, step) lets you choose both direction and spacing. The start is included if the range is nonempty. The stop is always excluded.

A range is not a prebuilt list. It stores a compact description of its values and supplies integers during iteration. Converting it with list() is useful for inspecting a small range, but materializing a huge range defeats its memory advantage. A range can be iterated again; it is not an exhausted one-use generator.

Read the stop as a boundary

print(list(range(4)))
print(list(range(2, 9, 2)))
print(list(range(5, 0, -2)))
print(list(range(2, 5, -1)))

Expected output

[0, 1, 2, 3]
[2, 4, 6, 8]
[5, 3, 1]
[]

For a positive step, values must stay below the stop. Starting at 2 and adding 2 yields 2, 4, 6, and 8; the next value, 10, is outside the boundary. The stop need not be a value that the sequence would land on. For a negative step, values must stay above the stop. Subtracting 2 from 5 yields 5, 3, and 1, but not -1.

The final range is empty because a negative step moves away from a larger stop. This is not an exception. A step of zero is different: it cannot describe forward progress and raises ValueError. Range arguments must be integers or compatible integer-index values; using an ordinary float such as 2.5 raises TypeError.

Build a multiplication schedule with an ordinary loop

The task is to display the first five multiples of seven, numbered from one. Five repetitions beginning at one need the exclusive boundary six. Multiplication computes a result; it does not modify the range or its loop variable.

number = 7
limit = 5
for multiplier in range(1, limit + 1):
    print(multiplier, "x", number, "=", multiplier * number)

Expected output

1 x 7 = 7
2 x 7 = 14
3 x 7 = 21
4 x 7 = 28
5 x 7 = 35

Trace the multiplier first, then the product. Changing the number to zero still performs five iterations and prints five zero products. Changing limit to zero creates range(1, 1), so there are no multiplication lines. For this exercise, define limit as a nonnegative integer; reject negative limits rather than silently treating a mistaken request as a valid empty schedule.

Count repetitions separately from labels

range(5) gives five repetitions labeled 0 through 4. range(1, 6) also gives five repetitions, labeled 1 through 5. That distinction matters when zero-based list positions meet human-facing row numbers. Do not assume the stop equals the number of values when a custom start or step is used.

When items already exist, direct iteration is usually clearer than constructing numeric indexes. Use enumerate() when you need an item and a display number. Reserve range for meaningful integer sequences, repeated steps, or positions actually required by the algorithm. Before running a loop, write its first value, last included value, and expected iteration count; this catches many off-by-one mistakes.

Runnable example and expected output

Setup: Python 3.10 or newer, standard library only. Save the following as lesson_024.py and run python lesson_024.py (or python3).

print(list(range(2,9,2)))
print(list(range(5,0,-2)))

Expected output:

[2, 4, 6, 8]
[5, 3, 1]

Walkthrough: Identify the initial variable values, follow the control flow in execution order, and write down every printed result. Change one input, predict the new output and then run the modified program.

Guided real-world project

This project applies range and numeric iteration to a practical scenario. Review the input values and decision or iteration rule before running the program.

def multiples(number, limit):
    """Return multiples for an integer number and nonnegative integer limit."""
    if type(number) is not int or type(limit) is not int or limit < 0:
        raise ValueError("number must be an integer; limit must be a nonnegative integer")
    results = []
    for multiplier in range(1, limit + 1):
        results.append(number * multiplier)
    return results

print(multiples(7, 5))

Expected output:

[7, 14, 21, 28, 35]

Testing plan: Run the shown sample, add an empty or minimum-size input where applicable, and test a value at the relevant boundary. For larger systems, separate the core calculation from user input so it can be tested independently.

Input contract: number is an integer and limit is a nonnegative integer; Boolean values are excluded. A zero limit returns an empty list. Invalid input raises ValueError, shown here as a small preview of explicit error reporting.

Optional preview: the original comprehension

After learning list comprehensions in lesson 035, compare the loop with [number * i for i in range(1, limit + 1)]. Apply the same validation first; the compact expression does not validate inputs.

Common mistakes and professional practices

  • Confusing an expression’s value with a side effect.
  • Skipping validation of inputs and collection sizes.
  • Misreading the order of operations or changes to state.
  • Forgetting to test zero, empty, minimum and maximum cases.
  • Using overly complicated logic instead of descriptive intermediate variables.

Debugging approach: Print the relevant state, compare each step with the expected result, isolate the first divergence, correct the underlying rule, and rerun all cases.

Think, trace, and solve

Attempt each question before revealing its answer. Explain your reasoning as well as the final result.

1. Predict a descending range

Write the exact result of list(range(8, 1, -3)) and explain why 1 is absent.

Optional hint

Subtract three repeatedly while the value stays above the exclusive stop.

Reveal answer and reasoning

Expected output

[8, 5, 2]

Each next value subtracts 3. The stop is exclusive, and the next candidate after 2 is -1, which is already below the descending boundary.

2. Count independently of the stop

count = 0
for value in range(3, 12, 4):
    count += 1
    print(value)
print("Count:", count)

Predict the output.

Optional hint

List the actual range values before counting them.

Reveal answer and reasoning

Expected output

3
7
11
Count: 3

The sequence has three included values. Twelve is a boundary, not the repetition count.

3. Diagnose an empty countdown

A learner writes range(5, 0) and expects 5 through 1. Why is it empty? Give the corrected expression.

Optional hint

An omitted step is positive one.

Reveal answer and reasoning

The omitted step defaults to positive 1, which cannot move from 5 toward the lower stop 0. Use range(5, 0, -1). It yields 5, 4, 3, 2, 1; zero remains excluded.

4. Distinguish errors from empty results

Classify each expression: list(range(4, 4)), range(1, 5, 0), and range(2.5).

Optional hint

An empty sequence is valid; a zero step and a float boundary are invalid calls.

Reveal answer and reasoning

The first produces [] because start equals stop. The second raises ValueError because the step cannot be zero. The third raises TypeError because an ordinary float is not accepted as an integer boundary. An empty range is a valid sequence, unlike the two invalid calls.

5. Include the requested endpoint

Print the even page numbers from 2 through 10 inclusive, one per line. Then explain why range(2, 10, 2) is insufficient.

Optional hint

Choose a stop beyond ten, then keep the step at two.

Reveal answer and reasoning
for page in range(2, 11, 2):
    print(page)

Expected output

2
4
6
8
10

The stop must lie beyond the final included value. A stop of 10 excludes 10. Using 11 makes 10 valid without introducing another even page.

Mastery checkpoint

Before advancing, explain the main concept without notes, predict the example output, run the project, and create at least three independent tests. If your results differ, revisit the debugging section.

Summary: Use range with start stop and step without off-by-one errors. Reliable programs combine clear logic, appropriate validation and repeatable testing.

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.