简体   繁体   中英

Python generator function confusion

Hey so I am working on a program that requires a day/night cycle. Here is the function that I made to get it to start working:

def epoch():
    for i in range(0,varb.run_number):
        print("it is now day")
        epoch_state = 1
        yield epoch_state
        time.sleep(varb.day_night_length)
        print("it is now night")
        epoch_state = 0 
        yield epoch_state
        time.sleep(varb.day_night_length)

I can find nothing wrong with it, but when I call it I get this:

<generator object epoch at 0x01036670>

Any ideas on how to fix this?

PS The idea here is to run the cycle while printing out the state and returning the state

PPS anything with varb. is a global with an unimportant numerical value

There is no error here. The function is working correctly.

You created a generator function by using yield expressions. You now need to iterate over your generator . Until you do, the generator is paused.

You could use list() for that:

result = list(epoch())

or a for loop:

for result in epoch():
    print(result)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM