Python Range

Python Range Function: A Beginner's Guide

The range() function returns a sequence of numbers, starting from 0 by default, increments by 1 (by default), and stops before a specified number.

It is commonly used with for loops to iterate a specific number of times.


1. Syntax of range()

The range() function can take up to three arguments:

range(start, stop, step)

2. Using Only the stop Parameter

If you only pass one argument to range(), it will treat it as the stop value. The sequence will start at 0.

Range with 1 Parameter

# Generates numbers from 0 to 4 (5 is not included)
for x in range(5):
  print(x)

3. Using start and stop Parameters

If you pass two arguments, the first is the start value and the second is the stop value.

Range with 2 Parameters

# Starts at 2, stops at 5 (6 is not included)
for x in range(2, 6):
  print(x)

4. Using the step Parameter

If you want the sequence to increment by a different number (like 2, 5, or even negative numbers), you can provide a third argument.

Range with Step Example

# Starts at 2, stops before 20, increments by 3
for x in range(2, 20, 3):
  print(x)

Exercise

?

What will range(1, 4) produce?