Python if块的可读性

Python if块的可读性,python,python-3.x,Python,Python 3.x,我在if语句中有一组非常长的表达式。但是很明显,我不允许分割if语句,即使我没有使用缩进分割块,这显然是因为python的原因。我对python完全是一个新手,所以如果我的问题很烦人,我很抱歉 理想情况下,我希望将if语句安排为: if (expression1 and expression2) or ( expression2 and ( (expression3 and expression4) or (expression3 and expression5) or ( expressio

我在
if
语句中有一组非常长的表达式。但是很明显,我不允许分割if语句,即使我没有使用缩进分割块,这显然是因为python的原因。我对python完全是一个新手,所以如果我的问题很烦人,我很抱歉

理想情况下,我希望将
if
语句安排为:

if (expression1 and expression2) or
(
expression2 and
(
(expression3 and expression4) or 
(expression3 and expression5) or
(
expression4 and (expression6 or expression7)
)
):
    pass

现在,所有内容都在一行中,可读性不强。

第一行可以使用旧式反斜杠,其他人不需要,因为您使用的是括号:

if (expression1 and expression2) or \
(
expression2 and
(
(expression3 and expression4) or
(expression3 and expression5) or
(
expression4 and (expression6 or expression7)
)
)
):
    pass

请注意,必须修复您的示例,因为缺少一个右括号。

使用\将表达式放在多行上,您甚至可以识别它以提高可读性:

if (expression1 and expression2) or \
(expression2 and \
    (\
    (expression3 and expression4) or \
    (expression3 and expression5) or \
        ( \
         expression4 and (expression6 or expression7) \
         )\
         ):
    pass

Python有几种允许多行语句的方法。在本例中,您可以将整个if条件简单地包装在括号中:

if ((expression1 and expression2) or
(
expression2 and
(
(expression3 and expression4) or 
(expression3 and expression5) or
(
expression4 and (expression6 or expression7)
)
)):
    pass
然而,我应该注意到,在一个
if
语句中包含这么多条件对我来说似乎有点代码味道。也许考虑创建助手函数来封装一些逻辑,或者使用多个<代码>如果语句。

你可以这样做:

t1_2=(expression1 and expression2)
t3_4=(expression3 and expression4)
t3_5=(expression3 and expression5)
t6_7=(expression6 or expression7)
if test1 or(expression2 and (t3_4 or t3_5 or(expression4 and t6_7)):
    pass

你可以用parens来包装整个过程,但是有那么多的表达式对我来说似乎有点代码味道;试着完全改变它。将其设置为局部变量或多个变量,以便为要检查的每个条件命名。然后你可以把它分解,使它更简短,同时更易读。你在最后缺少了一个括号,这可能是因为OP留下了一个语法错误(省略了一个右括号),只是为了误导我们。