简体   繁体   中英

Breaking out of nested loop in python turtle

i want two 'items' to move at once using this loop:

import turtle as t
from turtle import *
import random as r
t1=Turtle()
t2=Turtle()
turtles=[t1,t2]
for item in turtles:
  item.right(r.randint(5,500))
c=0
for i in range(500):
    for item in turtles:
       item.forward(2)
       c=c+1
       if c==1:
         yc=item.ycor()
         xc=item.xcor()
       if c==2:
         c=0
         yc2=item.ycor()
         xc2=item.xcor()
       if yc-yc2<5 or xc-xc2<5:
         break  #here is my problem
#rest of code

I want to exit my program using the break line if the object are on the same x or y line up to the nearest 5, but instead one of the objects freeze and the other one keeps going until the loop is over. How can i make my program exit that loop instead?

Your break statement does not work the way you want because it's a nested loop.

You should use exceptions:

try:
    for i in range(500):
        for item in turtles:
            ...
            if yc - yc2 < 5 or xc - xc2 < 5:
                raise ValueError
except ValueError:
    pass

However, you must take care not to pass through any unanticipated errors that you should actually catch!


Consider putting your code into a function to avoid all this hassle:

def move_turtles(turtles):
    for i in range(500):
        for item in turtles:
            ...
            if yc - yc2 < 5 or xc - xc2 < 5:
                return

move_turtles(turtles)
# rest of code

This is known as breaking out of a nested loop. Here is one solution, among many.

stop = False

for j in i:
    if stop:
        break
    #Do stuff
    for k in j:
        #Do more stuff
        if (condition):
            stop = True
            break #breaks (for k in j) loop

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM