Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why yield does not work in this construct?

I cannot understand why this yield construct gives me only one run in the for loop:

class myRange():
    def __init__(self, first, last):
        self.current = first - 1
        self.last = last

    def __iter__(self):
        self.current = self.current + 1
        if (self.current <= self.last):
            yield self.current


for n in myRange(1, 10):
    print(n)

which produces:

1

EDIT: Kind of weak question! I was tricked by the name of the __iter__ funciton…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Your __iter__ function needs to loop. As it is, it only yields once, so your loop only prints one value.

class myRange():
    def __init__(self, first, last):
        self.current = first
        self.last = last

    def __iter__(self):
        while self.current <= self.last:
            yield self.current
            self.current += 1
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading