简体   繁体   English

如何在while循环中运行两个while循环

[英]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 我尝试使用for循环(用于range(0,3)中的情节),删除情节var甚至定义

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 打印出第一个嵌套的while循环(while情节<3)

Episode 0
Episode 1
Episode 2

then the second nested while loop prints out "hi" for 15 seconds 然后第二个嵌套的while循环将输出“ hi” 15秒钟

and then the first nested while loop should print out 然后应该打印出第一个嵌套的while循环

Episode 0
Episode 1
Episode 2

and then the print "hi" for 15 seconds again and so forth. 然后再次打印“ hi” 15秒,依此类推。 It should repeat this process forever (hence the while True: loop). 它应该永远重复此过程(因此while True:循环)。

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. Python为您提供了帮助这一点的工具。 The for statement gives you a counting loop in one convenient package: for语句在一个方便的程序包中为您提供了一个计数循环:

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. 请注意,结束时间也有相同的问题:您需要为外部while循环的每次迭代重新计算它,因此代码应恰好在while True语句之后。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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