Breaking out of nested while True loop

Viewed 176

I am running a while True: loop in a webscraping script. I want the scraper to run in an incremental loop until running into a certain error. The general question is about how to break out of a while True loop when a certain condition is matched. The code as is just keeps on outputting the first run forever:

output 1;1
...
output 1;n

This is a minimal reproducible example of my code.

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

The desired output is:

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]
1 Answers

You don't need try and except here. Keep things simple and just use a simple while condition on your go variable. In that case, you don't even need a break because as soon as go>=3, the condition will be False, you will come out of the while loop and restart the while loop for the next value of 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

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

Alternative to while : As suggested by @chepner, you don't even need while and are better off with a for loop over go as

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