Python iterator returning unwanted 'None' -
why iterator returning 'none' in output. parameters/example below, getting [none,4,none] instead of desired [4] can explain why getting none , how can fix it? print out 'returning' appears once assuming 1 item should appended returning calling function.
code:
class prizes(object): def __init__(self,purchase,n,d): self.purchase = purchase self.length = len(purchase) self.i = n-1 self.n = n self.d = d def __iter__(self): return self def __next__(self): if self.i < self.length: old = self.i self.i += self.n if (self.purchase[old])%(self.d) == 0: print("returning") return old+1 else: raise stopiteration def superprize(purchases, n, d): return list(prizes(purchases, n, d)) purchases = [12, 43, 13, 465, 1, 13] n = 2 d = 3 print(superprize(purchases, n, d)) output:
returning [none, 4, none]
as people in comments have pointed out, line if (self.purchase[old])%(self.d) == 0: leads function returning without return value. if there no return value supplied none implied. need way of continuing through list next available value passes test before returning or raising stopiteration. 1 easy way of doing add else clause call self.__next__() again if test fails.
def __next__(self): if self.i < self.length: old = self.i self.i += self.n if (self.purchase[old])%(self.d) == 0: print("returning") return old+1 else: return self.__next__() else: raise stopiteration
Comments
Post a Comment