CodingNic

Loops and Iteration

Range Function

Loops and Iteration 18 min read

Range Function

Range Function

When using loops, you will often want to repeat something a certain number of times.

For example:

  • Print numbers from 1 to 5
  • Repeat a message 3 times
  • Count from 10 down to 1

Python gives us a helpful tool for this called range().

What Is Range?

range() creates a sequence of numbers.

It is commonly used with a for loop.

python
for number in range(5):
    print(number)

What Happens Here?

Python creates numbers starting from 0.

So the output is:

text
0
1
2
3
4

It stops before 5.

Start and Stop

You can choose where to start.

python
for number in range(1, 6):
    print(number)

Output:

text
1
2
3
4
5

The first number is the start.

The second number is where to stop (not included).

Step Value

You can also choose how much to move each time.

python
for number in range(2, 11, 2):
    print(number)

Output:

text
2
4
6
8
10

This counts by 2.

Counting Backwards

Use a negative step.

python
for number in range(5, 0, -1):
    print(number)

Output:

text
5
4
3
2
1

Code Along

python
for number in range(1, 4):
    print("Hello", number)

Mini Challenge

Build a number printer.

Steps:

  • Use range()
  • Print numbers from 1 to 10

Real World Use Case

Programs use range() for counting items, repeating tasks, generating numbers, and creating timers.

Quiz

  1. What does range() create?
  2. Does range(5) include 5?
  3. What does the third value in range() do?
  4. How do you count backwards?

Assignment

Create a program that prints even numbers from 2 to 20 using range().

Summary

You learned how range() creates numbers for loops, how start and stop work, and how to count forward or backward.