gpt4 book ai didi

python - 打破python turtle中的嵌套循环

转载 作者:太空宇宙 更新时间:2023-11-04 08:35:59 25 4
gpt4 key购买 nike

我希望使用此循环同时移动两个“项目”:

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

如果对象在相同的 xy 行上,我想使用 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

关于python - 打破python turtle中的嵌套循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48967114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com