if 语句到一行 return

if statement to one line with return

我知道 'one line if statement' 问题已经被问过多次,但我无法弄清楚我的代码有什么问题。我要转换

def has_no_e(word):
    if 'e' not in word:
        return True

单行函数,如:

def hasNoE(word):
    return True if 'e' not in word

但是如果我这样做会出现语法错误 - 为什么?

三元条件语句要求您在其中也有一个 else。因此,您必须:

def hasNoE(word):
    return True if 'e' not in word else False

我认为是因为您没有指定 else 部分。你应该写成:

return True if 'e' not in word else None

这是因为 Python 将其视为:

return <expr>

并且您将 三元条件运算符 指定为 <expr>,其语法为:

<expr1> if <condition> else <expr2>

所以 Python 正在寻找您的 else 部分。


Return False?

也许您想 return False 以防测试失败。在那种情况下,你可以这样写:

return True if 'e' not in word else False

但这可以缩短为:

return 'e' not in word