简体   繁体   中英

how to run two while loops inside a while loop

interval_sec = 15.0
t_end = time.time() + interval_sec
episode = 0
while True:

    while episode < 3:
        print('Episode %s' % episode)
        episode += 1

    while time.time() < t_end:           
        print("hi")

I've tried everything. I tried using a for loop (for episode in range(0,3)), deleting the episode var and even defining the

while episode < 3:
    print('Episode %s' % episode)
    episode += 1

as a function in the loop.

The expected output I am trying to achieve, in pseudo code, is:

the first nested while loop (while episode < 3:) prints out

Episode 0
Episode 1
Episode 2

then the second nested while loop prints out "hi" for 15 seconds

and then the first nested while loop should print out

Episode 0
Episode 1
Episode 2

and then the print "hi" for 15 seconds again and so forth. It should repeat this process forever (hence the while True: loop).

Looking for a fix that I haven't tried. Much appreciated

Your counting logic for the first loop is wrong. Looks at the basic pieces of initialization, test, and increment:

episode = 0
while episode < 3:
    ...
    episode += 1

This forms the basic counting loop. The problem is that you separated the pieces, placing them in different logic blocks:

episode = 0
while True:       # This is fatal to your counting loop's operation
    while episode < 3:
        ...
        episode += 1

Python gives you tools to help with this. The for statement gives you a counting loop in one convenient package:

for episode in range(3):
    ....

Now it's trivial to keep the loop pieces together.

Note that you have the same problem with the ending time: you need to recompute it for each iteration of the outer while loop, so that code should come just after the while True statement.

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