我希望使用此循环同时移动两个“项目”:
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
如果对象在相同的 x 或 y 行上,我想使用 break 行退出我的程序,直到最接近的 5 ,而是其中一个对象卡住,而另一个对象继续运行,直到循环结束。我怎样才能让我的程序退出那个循环?
请您参考如下方法:
您的 break 语句无法按您希望的方式工作,因为它是一个嵌套循环。
你应该使用异常:
try:
for i in range(500):
for item in turtles:
...
if yc - yc2 < 5 or xc - xc2 < 5:
raise ValueError
except ValueError:
pass
但是,您必须注意不要忽略任何您实际上应该捕获的意外错误!
考虑将您的代码放入函数中以避免所有这些麻烦:
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
