I have this nested loop in my project (it's a lot more complicated of course I just simplify it so you can see what I mean). I know there is no label and goto in python, I just want to show what I want to do.
From line #goto third I want go back to place where you can see #label third.
I tried different setups of my loops but they never do what I want
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()
Every path in this nested loops seems to work fine but I want my loop to go back to #label third from #goto third and it goes back to #label first. How can I change my loops to make it possible?
1 Answer 1
Actions like goto first which break 'for' loops are evil in many ways. While loops are more elegant, but maybe a 'state machine' like solution is better for you. Something like:
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>
A state machine permits much more flexibility. Also, it won't cause as much indentation as nested loop. If the complexity gets larger, there are some libraries which can help you. Interesting links on Finite State Machines (FSM):
https://python-3-patterns-idioms-test.readthedocs.io/en/latest/StateMachine.html
goto thirdtolabel firstwhen thefor y in range(5)loop completes for every x. If you want more loop control, then I suggest using awhileinstead of afor