Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

A variable to return a number once, then 0 afterwards

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading