0

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.

7
  • 2
    Why do you think range should return more than once? It chooses one of the 3 yields when called, and does nothing after that. Commented Nov 15, 2020 at 13:30
  • 1
    like @ScottHunter said your generator will yield once. You need to create a loop in your generator function.
    – Rob
    Commented Nov 15, 2020 at 13:31
  • How would I make it return values as long as the for loop is iterating through it? Commented Nov 15, 2020 at 13:32
  • 1
    @AnuragSaksena the loop must be in the generator function.. around all the logic for your yeilds.. Remember to have a exit condition or you will loop forever tho.
    – Rob
    Commented Nov 15, 2020 at 13:34
  • For positive step values, all you need is 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.
    – ekhumoro
    Commented Nov 15, 2020 at 14:01

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.