简体   繁体   English

突破python乌龟的嵌套循环

[英]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. 如果对象在同一xy线上直到最接近的5,我想使用break退出程序,但是其中一个对象冻结,而另一个对象一直循环直到循环结束。 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. 您的break语句无法正常运行,因为它是一个嵌套循环。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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