Nov-24-2020, 05:40 PM
I think putting a print statement in odd_numbers() is bad design. It makes the function useless. I cannot use your odd_numbers() to get a list of odd numbers for the program I am writing. I don't want the printing numbers side effect messing up the output in my program.
For something like this maybe I want a generator.
For something like this maybe I want a generator.
def odd_numbers(start=1, end=None): if start % 2 == 0: start += 1 while True: if end and start > end: break yield start start += 2 # If I want to print odd numbers print('Count from 11 to 21 by 2') for x in odd_numbers(11, 21): print(x) # If I want a list of odd nmbers a = list(odd_numbers(1, 7)) b = [x for x in odd_numbers(13, 21)] print('Combined lists =', a+b) # Or an unknown number of odd numbers odds_gen = odd_numbers() odds = [] while sum(odds) < 100: odds.append(next(odds_gen)) print(f'sum{odds} = {sum(odds)}')You would never do something like this for odd numbers. They are way too easy to generate ad hoc. But you might do this for a different sequence that is not so easy to generate and that might have several different uses.