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)
The last number (3, 5) is not included!
Example Code
What Happens
It prints from 0 to 4 (5 doesn't appear!)
Quiz
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
Cause:range(n)only generates up to n-1
โ Correct Code
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.
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!
๐งฉ 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?