Reputation: 21
I get the values but it also prints 'None' for non prime values
class Prime:
def __init__(self, n1, n2):
self.n1 = n1
self.n2 = n2
def __iter__(self):
return self
def __next__(self):
num = self.n1
self.n1 += 1
for x in range(2, num):
if num % x == 0:
break
else:
return num
z = Prime(30, 200)
for k in z:
print(k)
results: None 31 None None None None None 37 None None None 41 None 43
Upvotes: 0
Views: 88
Reputation: 1432
If a break
is encounted in a for/else loop in Python, the else
block is never executed. Hence, None
is returned by default. That is almost certainly the root cause of your error.
Your function should probably look like this:
def __next__(self):
num = self.n1
self.n1 += 1
for x in range(2, num):
if num % x == 0:
break
return num
(Although now that I look at it, that for
loop should probably be a while
loop, I am not sure your logic is correct here)
Upvotes: 2