首页 > 解决方案 > 打破嵌套的while True循环

问题描述

while True:在网页抓取脚本中运行一个循环。我希望刮板以增量循环运行,直到遇到某个错误。一般问题是关于当某个条件匹配时如何跳出while True循环。代码只是永远输出第一次运行:

output 1;1
...
output 1;n

这是我的代码的最小可重现示例。

runs = [1,2,3]

for r in runs:
    go = 0
    while True:
        go +=1
        output = ("output " + str(r) + ";" +str(go))
        try:
            print(output)
        except go > 3:
            break

所需的输出是:

output 1;1
output 1;2
output 1;3
output 2;1
output 2;2
output 3;3
output 3;1
output 3;2
output 3;3
[done]

标签: python

解决方案


你不需要tryexcept这里。保持简单,只需对变量使用简单的while条件。go在这种情况下,您甚至不需要 abreak因为只要go>=3条件为False,您将退出 while 循环并重新启动 while 循环以获取 的下一个值r

runs = [1,2,3]

for r in runs:
    go = 0
    while go <3:
        go +=1
        output = ("output " + str(r) + ";" +str(go))
        print(output)

输出

output 1;1
output 1;2
output 1;3
output 2;1
output 2;2
output 2;3
output 3;1
output 3;2
output 3;3

while 的替代方案:正如@chepner 所建议的那样,您甚至不需要while并且最好使用 for 循环go作为

for r in runs:
    for go in range(1, 4):
        output = ("output " + str(r) + ";" +str(go))
        print(output)

推荐阅读