Search code examples
pythonpython-3.xnested-loopsbreakturtle-graphics

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?


Solution

  • 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