为什么循环会错过检查条件

Why does loop miss checking condition

我有一个小循环让海龟在遇到正方形的角后转 90 度。第一个循环很好,但是 Python 似乎忘记在下一个循环中检查条件。

我开始画画的时间是

t.setpos(-300,300)

第一个循环工作正常:

for i in range(4):
t.forward(600)
print(t.pos())
if t.pos() > (300,300):
    t.right(90)
elif t.pos() > (300,-300):
    t.right(90)
elif t.pos() > (-300, -300):
    t.right(90)
elif t.pos() > (-300,300):
    t.right(90)

但是当我将 range() 增加到 5 时,代码忘记检查 elif t.pos() > (-300,300):t.right(90) 而是 Python 继续绘制 t.forward(600) 到本职位:

(-300.00,900.00)

for i in range(5):
t.forward(600)
print(t.pos())
if t.pos() > (300,300):
    t.right(90)
elif t.pos() > (300,-300):
    t.right(90)
elif t.pos() > (-300, -300):
    t.right(90)
elif t.pos() > (-300,300):
    t.right(90)

知道为什么 Python 会忘记检查这样的条件吗?怎么感觉哪里做错了。

这是我的解决方案,它可能效率不高,但它确实有效...

if myturtle[count].xcor() > 300 and myturtle[count].heading() == 0:
   myturtle[count].right(90)
if myturtle[count].ycor() < -300 and myturtle[count].heading() == 270:
   myturtle[count].right(90)
if myturtle[count].xcor() < -300 and myturtle[count].heading() ==180:
   myturtle[count].right(90)
if myturtle[count].ycor() > 300 and myturtle[count].heading() == 90:
   myturtle[count].right(90)

看似简单的修复是这个比较是落后的:

elif t.pos() > (-300, 300):

应该是:

elif t.pos() < (-300, 300):

您在 range(4) 情况下看不到它的原因是循环在执行之前就退出了。在 range(5) 的情况下它最终执行并且反向比较导致失败。

但是,此代码存在重大问题,在您构建它时会出现这些问题。虽然你的调试print(t.pos())语句显示:

(300.00,300.00)
(300.00,-300.00)
(-300.00,-300.00)
(-300.00,300.00)
(-300.00,900.00)

真正发生的事情是:

(300.0, 300.0)
(300.00000000000006, -300.0)
(-299.99999999999994, -300.00000000000006)
(-300.00000000000006, 299.99999999999994)
(-300.00000000000017, 900.0)

你看不到这个的原因是因为 t.pos() 不是 return 通用 tuple,它 return 是 tuple 称为 Vec2D,它有自己的 repr() 方法,通过仅显示两位数的精度来掩盖浮点模糊性:

 def __repr__(self):
        return "(%.2f,%.2f)" % self

您可能希望您的子句按顺序触发,但它们不会:

职位:(300.0, 300.0)

触发第二个子句:elif t.pos() > (300,-300):

职位:(300.00000000000006, -300.0)

trips 第一个子句:if t.pos() > (300,300):

职位:(-299.99999999999994, -300.00000000000006)

trips 第三个子句:elif t.pos() > (-300, -300):

和职位:

(-300.00000000000006, 299.99999999999994)
(-300.00000000000017, 900.0)

不要违反任何条款。添加一些 print() 语句让自己相信这一点。