Skip to content

B. range() Number Factory


๐ŸŽฏ Learning Goals

By the end of this lesson, you'll be able to:

  • โ—‹ range() You understand what a function is
  • โ—‹ Understand why it starts from 0
  • โ—‹ range()Learn the numbers it makes

Core Concepts

What is range()?

range() A function Number factoryIt is!

๐Ÿญ Analogy: a number factory

If you order "make me 5!" at the number factory, it makes 0, 1, 2, 3, 4!

range() results

Code the numbers it makes Count
range(3) 0, 1, 2 3
range(5) 0, 1, 2, 3, 4 5 of them
range(8) 0, 1, 2, 3, 4, 5, 6, 7 8

Why start from 0?

Python It counts from 0 (0-based indexing)

range(3)  # 0, 1, 2 (3 total)
range(5)  # 0, 1, 2, 3, 4 (5 total)

The last number (3, 5) is not included!


Example Code

# Checking range()
for i in range(5):
    print(i)

# Output:
# 0
# 1
# 2
# 3
# 4

What Happens

It prints from 0 to 4 (5 doesn't appear!)


Quiz

Quiz: range(5)
range(5)which numbers does it make?
Show Answer

Answer: B) 0, 1, 2, 3, 4

range(5)makes 5 numbers total, from 0 up to 4. The last number, 5, is not included!

range() syntax practice:

range()is a function that makes numbers. range(n)makes n numbers total, from 0 up to n-1:

  • 0, 1, 2, 3, 4 To make this (5 numbers): range( )
  • 1, 2, 3, 4, 5 To make this (starting from 1): range( , 6)
  • range(3)the numbers it makes:

๐Ÿ”ง Debug Clinic

Problem: it repeats one fewer time than expected

โŒ Wrong Code

# When you want 1 through 5
for i in range(5):
    print(i+1)  # 1, 2, 3, 4, 5 (works but complicated)
Cause: range(n)only generates up to n-1

โœ… Correct Code

for i in range(1, 6):  # Specify start and end
    print(i)  # 1, 2, 3, 4, 5
Fix: range(start, end)Specify the starting point with this!


Try Coding It Yourself

Take what you learned with the blocks and write it yourself in Python code!

Printing numbers with range()

range(5)Print out the numbers it makes for yourself.

Example Answer
for i in range(5):
    print(i)

Result: 0, 1, 2, 3, 4 are printed!

Specifying a starting point

range(1, 6)Use this to print from 1 to 5!


๐ŸŽฏ Fill-in-the-Blank Mission

Fill in the blanks to complete the code!

Check answers
for i in range(5):
    print(i)
Check answers
for i in range(3, 8):
    print(i)

๐Ÿงฉ Key Takeaways

What you learned in this lesson:

Concept Description
range(n) Generates numbers from 0 to n-1
Starts from 0 Python uses 0-based indexing
Last number The specified number is not included
range(start, end) Generates from start to end-1

Review Checklist

  • [ ] range() Can you explain what the function is?
  • [ ] range(5)Do you know which numbers it makes?
  • [ ] Do you understand why it starts from 0 and the last number isn't included?