1

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?

0

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

5 Comments

Don't bother making your own Exception class, there's just no need and it obfuscates your code
@KindStranger Duly noted. Updated the answer as well.
Doesn't this drag us into the issue exceptions as control flow considered a serious antipattern since exceptions are being used for things that aren't really exceptional? And if this really is an exceptional case, then reusing a non-applicable existing exception to save effort seems the wrong thing to do.
@cdlane Python endorses EAFP style of coding, and thus exceptions are pretty cheap compared to other languages. However, you can hear arguments from both sides regarding this issue.
@cdlane Please check my updated answer. You might be more comfortable with that. :)
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.