[Python] Problem with nested loop logic and indentation in python

Discussão em 'Python' iniciado por Stack, Agosto 10, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to re-run a nested for loop within a while loop if the while condition is not met. If the condition is met then I want the inner loop to terminate and proceed to the next iteration of the outer loop. I want to try the inner loop 10 times before preceding to the next i of the outer loop. I've tried various variations of the following (psuedocode) but am unsure exactly what the if / else statements at the end the function should say, break/continue? And where they should be indented to accomplish this. I've appended the indentation lengths to each part of the code. I would be grateful if anyone can help explain if it's possible to do this and how to do it. Thanks in advance.

    def function(input):

    counter1 = 0

    for i in range(0, 10): #indent5 - outer loop
    #assign some stuff to variables based on value of i...
    counter2 = 0
    var1 = cats
    var2 = dogs
    x = len(input)

    MAX_RETRIES = 10
    attempts = 0

    while attempts < MAX_RETRIES and counter2 < x: #indent9

    for var in var1 : #13 - inner loop
    if blah == blah: #indent17
    #do a lot of stuff here with cats and dogs...
    random.choice(etc, etc)
    #nested ifs
    if blahblah == blahblah: #indent21
    counter1 += 1
    if blahblahblah == blahblahblah: #indent21
    counter2 += 1

    if at end of inner loop counter2 == x: #indent where?
    #go to next iteration of OUTER loop
    break / continue ? #?

    else: #indent where?
    #repeat INNER loop - how?
    break / continue ?
    #reduce counter1 by value of counter2
    counter1 -= counter2
    #reset counter2 to 0 to start inner loop again
    counter2 = 0

    return blah

    Continue reading...

Compartilhe esta Página