Changed the code so many times it doesn’t even run now. I don’t know what I’m doing to be frank.
Trying to make a user entered starting point for single use in a generator function and have it return 0 thereafter.
def selfDestruct(max=1):
throwaway = 255 # enter manually starting point
n = 0
if n < max:
n += 1
elif n >= max:
throwaway = 0
print(throwaway)
print(throwaway)
>Solution :
I’m not sure what your original code was really trying to do, but "generator function that generates up to a given value, then produces 0 afterwards is pretty easy:
from itertools import repeat
def selfDestruct(max=1):
yield from range(max) # Use max + 1 if it should produce max itself
yield from repeat(0) # We finished yielding the range, now we yield 0 forever
If you don’t want to use range or itertools.repeat it’s not much harder:
def selfDestruct(max=1):
n = 0
while n < max: # <= max to include max itself
yield n
n += 1
while True: # Infinite loop yielding 0 forever
yield 0
You use it with a standard for construct, though you’ll need break or itertools.islice involved to prevent the generator from continuing forever:
lasti = None
for i in selfDestruct(10):
print(i)
if lasti == i:
break # See the same number twice in a row (the trailing zeroes) and we stop
lasti = i