如何正确使用嵌套循环

How to use nested loops propely

我的项目中有这个嵌套循环(当然它要复杂得多,我只是对其进行了简化,以便您明白我的意思)。我知道python里面没有label和goto,我只是想展示我想做的事情。

从行 #goto third 我想回到你可以看到的地方 #label third

我尝试了不同的循环设置,但它们从来没有按照我的意愿行事

import time

onoff = "on"

t=0

while onoff == "on":
    #label first
    for x in range (5):
        print("first loop")
        time.sleep(1)
        for y in range (5):
            print("second loop")
            time.sleep(1)
            p = 0    #for testing
            t=0   #for testing
            if p != 5:
                if t == 0:
                    print("third loop")
                    time.sleep(1)
                    p2 = 5    #for testing
                    t=0
                    if p2 != 5:   #label third
                        if t == 0:
                            print("go back to first loop")
                            time.sleep(1)
                            #goto first
                        else:
                            print("lock")
                            #lock.acquire()
                    else:
                        if t == 0:
                            print("go back to third loop")
                            p2 = 3
                            time.sleep(1)
                            #goto third
                        else:
                            print("lock")
                            #lock.acquire()
                else:
                    print("lock")
                    #lock.acquire()

此嵌套循环中的每条路径似乎都可以正常工作,但我希望我的循环从 #goto third 返回到 #label third,然后它首先返回到 #label。我怎样才能改变我的循环使其成为可能?

goto first 这样打破 'for' 循环的行为在很多方面都是邪恶的。 While 循环更优雅,但也许 'state machine' 之类的解决方案更适合您。类似于:

state = 0
while is_on:
   if state == 0:             # do outer loop things
       <do things>
       state = 1              # to do inner loop things

   elif state == 1:
       n = 0
          # do inner loop things 
       n += 1
       if n == 5:
           state = 0

   elif state == 2:            # do even more nested things
       p = 0
       if <some condition>:
           state = 0
       p += 1
       if p == 5:
          state = <whatever>

状态机允许更多的灵活性。此外,它不会像嵌套循环那样导致缩进。如果复杂性变大,有一些库可以帮助你。有限状态机 (FSM) 上的有趣链接:

https://python-3-patterns-idioms-test.readthedocs.io/en/latest/StateMachine.html

https://www.python-course.eu/finite_state_machine.php