7. Range n

range() is a built-in function that produces a sequence of numbers. The one-argument form is:

  • stop — the number where the sequence stops. It is excluded.
  • The sequence starts at 0 and moves by 1, so range(3) gives 0, 1, 2.
  • range() returns a range object, not a list. In a for loop you use it directly.

When you do not need the number itself, use _ as the loop variable by convention: for _ in range(3): means "repeat three times".

Coming from JavaScript? range(n) replaces the classic for (let i = 0; i < n; i++). The stop is excluded, and range is lazy, not an array.

#01

Loop from zero

Loop over range(3) and print each number.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Start printing at one

Loop over range(5) and print each number plus 1.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Repeat a message

Use for _ in range(3) to print Hi three times. The name _ means the number itself is not used.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Print squares

Loop over range(4) and print each number squared with **.

Print exactly:

Create a free account to save your progress and unlock chapter 2.