I'm new to Python and I am trying to implement the range() object with positive step values as an iterator using a generator function in Python. I have already implemented this iterator by defining a class:
class ranges:
def __init__(self, start, stop, step):
self.start = start - step
self.stop = stop
self.step = step
def __iter__(self):
return self
def __next__(self):
self.start = self.start +self.step
if self.step > 0:
if self.start < self.stop:
return self.start
raise StopIteration
if self.step ==0:
return self.start - self.step
But when I try to create this iterator using a generator function, the program fails prematurely.
def range(start, stop, step):
range.counter = range.counter + 1
if step == 0:
yield start
elif step > 0:
if range.counter == 1 and start < stop:
yield start
elif (start + step) < stop:
start = start + step
yield start
range.counter = 0
for i in range(3, 11 , 2):
print(i)
The output should be 3, 5, 7, 9 but the output displayed is just 3.
range
should return more than once? It chooses one of the 3 yields when called, and does nothing after that.def range(start, stop, step): while start < stop and step > 0: yield start; start += step
. It makes no sense to accept a step of zero, since that would loop forever.