liveBook · Manning

Range

As explained in Get Programming: Learn to code with Python

A range expression is a Python expression that produces an arithmetic progression of integers, typically starting at zero and ending before a specified endpoint.

A range expression creates a sequence of integers for a for loop. With one number, range(N) starts at 0 and stops before N, producing 0 through N − 1. That gives a loop exactly N repetitions. section 16.3

Counting from zero

for v in range(3): print("var v is", v) Python assigns 0, then 1, then 2 to v, executing the indented print statement after each assignment. section 16.3

Customize the sequence with up to three numbers:

  • range(end) starts at 0 and uses a step of 1; range(5) produces 0, 1, 2, 3, 4. section 17.1
  • range(start, end) begins at start, uses a step of 1, and excludes end; range(2, 6) produces 2, 3, 4, 5. section 17.1
  • range(start, end, step) controls the increment; range(2, 9, 2) produces 2, 4, 6, 8. section 17.1
  • A negative step counts downward, as in range(6, 2, -1), which produces 6, 5, 4, 3; incompatible directions produce no values. section 17.1

Use range when a loop needs integer values or a fixed number of repetitions. For loops can also iterate directly over other sequences, such as the characters in a string. section 16.4 section 17.3

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains one-, two-, and three-argument forms, exclusive endpoints, steps, descending ranges, and loop execution.
Examples
Uses range(3), unrolled assignments, countdowns, even-number checks, and repeated messages.
What it assumes
Assumes basic for-loop structure and integer values while teaching range defaults, endpoints, and steps.
What you can do after
Apply it via Python for loops to repeat statements and generate customized integer sequences.
How it connects
Connects range to for loops, loop variables, sequences, integer counting, and string iteration.

Also explained in

Compare how 8 books explain range →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.