Reputation: 135
I am trying to produce a list of odd numbers using a generator (just to get a better insight into generators). I wrote the following code but, it doesn't stop running! While I expect the code stops when the condition i>n meets. Any help is appreciated.
import sys
def odd(n):
i=0
while True:
if i%2==0:
continue
yield i
i+=1
if i>n:
return
# Here we build a generator
g = odd(10)
while True:
try:
print(next(g),end=' ')
except StopIteration:
sys.exit()
Upvotes: 0
Views: 962
Reputation: 5564
In my opinion, you have two style issues in your code that make it hard to see the problem:
The use of continue
. A simple if
statement would make it easier to see which code might not execute and which code will definitely execute. continue
is mainly useful when you have nested if
statements making things complicated.
You don't utilize the while
condition. This assumes that the while
loop will have to execute at least once. When writing a loop, you should generally consider what happens if the loop needs to execute 0 times. What if someone passes an argument of -1
? What if you change the initial value of i
to 1 to save an iteration?
def odd(n):
i = 0
while i <= n:
if i % 2:
yield i
i += 1
# Automatically return and throw StopIteration.
Upvotes: 0
Reputation: 532238
When i
is even, you don't increment it, so it stays even for every subsequent iteration of the loop and never gets larger than n
.
You want to increment i
whether or not it is even.
def odd(n):
i=0
while True:
if i%2 != 0: # yield i only if it is odd
yield i
i+=1 # Increment i in either case
if i>n:
return
Upvotes: 2