Python中的Shrink double if语句

2024-04-26 03:29:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我不能使用以下语句,因为xy可以定义为None

if x*y > 9:
    pass

unsupported operand type(s) for *: 'NoneType' and 'NoneType'

所以我应该先检查一下是否存在:

if x and y:
    if x*y > 9:
        pass

这似乎有点多余。有没有更好的方法来实现这一点?你知道吗


Tags: and方法noneforif定义typepass
3条回答

你可以做:

if x and y and x*y > 9:
    pass

如果您得到更多的检查,使用all可能会更舒服:

if all([
    x,
    y,
    x*y > 9,
    other conditions,...]):
    pass

虽然if x and y and x * y > 9:是最直接的方法,但我发现另一种难以定义的方法是在xy错误时使用默认值:

if (x or 0) * (y or 0) > 9:

因为用0替换任何一个值都会使结果为0,所以当任何一个值为None时,测试都不会通过。这是因为Python boolean andor不返回TrueFalse它们返回最后一个计算值(已经是truthy或falsy)。所以,如果x是一个非零数,则使用x,否则使用0,对于y也是如此。你知道吗

根据EAFPEasier toAskForganity thanpermission)协议,以下是使用try and except的替代方法:

try:
   if x * y > 9:
       pass
except TypeError:
   pass

相关问题 更多 >