0
0
PythonHow-ToBeginner · 3 min read

How to Use Range in For Loop in Python: Simple Guide

In Python, use range() inside a for loop to repeat actions a set number of times. The range() function generates a sequence of numbers, which the loop goes through one by one.
📐

Syntax

The range() function can be used in three ways inside a for loop:

  • range(stop): Counts from 0 up to but not including stop.
  • range(start, stop): Counts from start up to but not including stop.
  • range(start, stop, step): Counts from start to stop (exclusive), moving by step each time.

This lets you control where counting starts, ends, and how much it jumps each time.

python
for i in range(stop):
    # do something with i

for i in range(start, stop):
    # do something with i

for i in range(start, stop, step):
    # do something with i
💻

Example

This example shows how to print numbers from 0 to 4 using range(stop), and then numbers from 2 to 6 using range(start, stop). It also shows counting backwards using range(start, stop, step).

python
print("Counting from 0 to 4:")
for i in range(5):
    print(i)

print("Counting from 2 to 6:")
for i in range(2, 7):
    print(i)

print("Counting backwards from 5 to 1:")
for i in range(5, 0, -1):
    print(i)
Output
Counting from 0 to 4: 0 1 2 3 4 Counting from 2 to 6: 2 3 4 5 6 Counting backwards from 5 to 1: 5 4 3 2 1
⚠️

Common Pitfalls

One common mistake is expecting range(stop) to include the stop number, but it actually stops before it. Another is forgetting that the step can be negative to count backwards. Also, using a step of zero causes an error.

python
print("Wrong: expecting 5 in output")
for i in range(5):
    print(i)  # This prints 0 to 4, not 5

print("Right: include 5 by using range(6)")
for i in range(6):
    print(i)

# Wrong: step cannot be zero
# for i in range(0, 5, 0):
#     print(i)  # This will cause an error

print("Right: use negative step to count backwards")
for i in range(5, 0, -1):
    print(i)
Output
Wrong: expecting 5 in output 0 1 2 3 4 Right: include 5 by using range(6) 0 1 2 3 4 5 Right: use negative step to count backwards 5 4 3 2 1
📊

Quick Reference

Remember these points when using range() in a for loop:

  • range(stop): from 0 up to but not including stop.
  • range(start, stop): from start up to but not including stop.
  • range(start, stop, step): from start to stop (exclusive), stepping by step.
  • Step can be negative to count backwards.
  • Stop is never included in the output.

Key Takeaways

Use range() in a for loop to repeat actions over a sequence of numbers.
range(stop) counts from 0 up to but not including stop.
range(start, stop) counts from start up to but not including stop.
range(start, stop, step) lets you control the counting step, including negative steps for backwards counting.
Remember that the stop number is never included in the loop.