Lesson 05
Python kvrange Generator — start, stop, step, and InputError
Learn kvrange as a bus route: start, stop, step, yield on each stop, next()+for handoff, InputError ticket, and inclusive stop vs range().
` inclusive
- Three-argument
start,stop,step, keyword args, customInputError - After some
next()calls, aforloop continues from the remaining values - The first
next()onkvrange(0, 0, 0)raisesInputError(generator body runs on first iteration) kvrangeis inclusive ofstop(unlike builtinrange())
The generator
class InputError(Exception):
pass
def kvrange(start=0, stop=0, step=1):
if (start == stop) and (stop == step):
raise InputError
if start >= stop:
stop = start
start = 0
while start <= stop:
yield start
start = start + stepThink of it like this
 is called again.
Try different routes in the playground
Change start, stop, and step in the playground below and watch the route change. Example: Start 10, Stop 20, Step 2.
` below).
How next() and for work together
You can consume two values with next(), then let a for loop continue from the remaining values.
print(next(r)) # 10 print(next(r)) # 12
for value in r: print(value)
14 16 18 20
The two-argument form uses the same idea: two `next(r1)` calls, then `for val in r1` prints the rest. A further `next(r1)` raises **`StopIteration`**.
## Two-argument kvrange
```python
def kvrange(beg, end):
while beg <= end:
yield beg
beg = beg + 1
r = kvrange(10, 20)
print(next(r))
while True:
try:
print(next(r))
except StopIteration:
breakDifferent ways to call kvrange
1. kvrange(10, 20, 2)
Bus starts at 10 and jumps 2 stops.
`
When start=5 >= stop=0, the logic converts this to 0 → 5.
`
Keyword arguments make the route clearer.
| Bus from 10 to 20, every 2 stops | |kvrange(5)| Start from depot (0) to Stop 5 | |kvrange(stop=6, step=2)` | Go to 6 using every second stop |
Other useful calls: kvrange(100, 120, 5), kvrange(25, 30) with default step 1.
Run the full script in the playground below.
InputError = invalid ticket
If someone gives the driver this ticket:
- Start = 0
- Stop = 0
- Step = 0
There is nowhere to go.
:
pass
if (start == stop) and (stop == step):
raise InputErrorHandling it:
try:
r5 = kvrange(0, 0, 0)
print(next(r5))
except InputError:
print("Check Start, stop and step Values:")Calling kvrange(0, 0, 0) only creates the generator object. The exception appears when next() starts executing the body.
Built-in range() vs kvrange()
| No — stops before destination | |kvrange(10, 20, 2)| Yes —while start <= stop` |
Python range(10, 21, 2) gives 10, 12, 14, 16, 18 (no 20). kvrange(10, 20, 2) includes the final stop 20.
Interview cheat sheet
| Topic | Answer |
|---|---|
| Keyword | yield |
| Inclusive? | Yes, <= stop |
| Empty / zeros | InputError on first next() |
| Partial consume | for continues after next() |
vs range() |
kvrange includes stop |
30-second recap
.
Loading playground…
Check your understanding
kvrange generator quiz
kvrange(beg, end) with two arguments is:
1 / 10