我正在用海龟建造一个蛇克隆体。在这个函数的内部是否有一种更干净/更复杂的写条件的方法?
def out_of_bounds(self, lst):
if lst.xcor() < -260 or lst.xcor() > 260 or lst.ycor() < -260 or lst.ycor() > 260:
return True发布于 2022-05-13 12:11:46
您可以通过取两个比较的绝对值来删除它们。
def out_of_bounds(self, lst):
return abs(lst.xcor()) > 260 or abs(lst.ycor()) > 260发布于 2022-05-13 12:08:42
使布尔表达式直接返回,也可以使用括号返回多行:
(移除行尾的\需要)
您的函数返回True或None,这是因为None是Falsy。如果表达式失败,最好返回False。
def out_of_bounds(self, lst):
return (
lst.xcor() < -260
or lst.xcor() > 260
or lst.ycor() < -260
or lst.ycor() > 260
)发布于 2022-05-13 12:11:14
大多数情况下,我会逆转那些测试并否定结果,我们保持在相同的状态,但更容易读懂。
在括号中,我们用xcor和ycor在±260区间进行测试,然后否定。
def out_of_bounds(self, lst):
return not (-260 <= lst.xcor() <= 260 and -260 <= lst.ycor() <= 260)https://stackoverflow.com/questions/72229334
复制相似问题