Using an iterator in python? -
i have learned iterators in python having hard time implementing them.
i trying write class loop works:
odds = oddnumbers(13) in odds: print(i)
i want write iter() function , next() function this.
so far have:
class oddnumbers: def __init__(self, number): self.number = number def __iter__(self): return self def __next__(self): current = self.number if self.number%2 == 0: return current else: raise stopiteration
but @ moment returning nothing. expect output be
1 3 5 7 9 11 13
help?
you need variable track current number:
def __init__(self, number): self.number = number self.current = 1
then need compare ending number, , maybe increment it:
def __next__(self): if self.current > self.number: raise stopiteration current = self.current self.current += 2 return current
Comments
Post a Comment