0
0
Pythonprogramming~5 mins

Iteration using range() in Python

Choose your learning style9 modes available
Introduction

We use range() to repeat actions a certain number of times easily. It helps us count from one number to another without writing many lines.

When you want to print numbers from 0 to 9.
When you need to repeat a task 5 times, like asking a question.
When you want to loop through a list by index.
When you want to create a sequence of numbers for a game score.
When you want to run a timer that counts seconds.
Syntax
Python
range(stop)
range(start, stop)
range(start, stop, step)

start is where counting begins (default is 0).

stop is where counting stops (not included).

step is how much to increase each time (default is 1).

Examples
Counts from 0 up to 4 and prints each number.
Python
for i in range(5):
    print(i)
Counts from 2 up to 5 and prints each number.
Python
for i in range(2, 6):
    print(i)
Counts from 1 to 9, skipping every other number (prints odd numbers).
Python
for i in range(1, 10, 2):
    print(i)
Sample Program

This program prints "Hello" followed by numbers 0, 1, and 2.

Python
for number in range(3):
    print(f"Hello {number}!")
OutputSuccess
Important Notes

The stop number is never included in the loop.

You can use negative step to count backwards, like range(5, 0, -1).

Summary

range() helps repeat actions by counting numbers.

You can control where to start, stop, and how much to step.

It is useful for loops that need to run a set number of times.