Custom Range Iterator
Lesson 10 of 13 in Coddy's Python Iterators course.
Challenge
EasyCreate a custom iterator class called StepRange that generates a sequence of numbers with a custom step size. This iterator should mimic the behavior of Python's built-in range() function but with more flexibility in step sizes.
The StepRange class should:
- Accept
start,stop, andstepparameters in its constructor - Implement the
__iter__()method to return the iterator object itself - Implement the
__next__()method to generate the next value in the sequence - Handle both positive and negative step sizes
- Raise a
StopIterationexception when the sequence is exhausted
After implementing the StepRange class, create an instance of it using the input values and print each generated number on a new line.
The following input will be provided:
- Three space-separated integers representing
start,stop, andstep
Try it yourself
# Read input
start, stop, step = map(int, input().split())
class StepRange:
def __init__(self, start, stop, step):
self.start = start
self.stop = stop
self.step = step
self.current = start
def __iter__(self):
return self
def __next__(self):
# TODO: Implement the __next__() method
pass
# Create an instance of StepRange
step_range = StepRange(start, stop, step)
# TODO: Iterate through the StepRange and print each value
# Remember to print each value on a new line