2

I have a very long set of expressions in a if statement. But apparently I'm not allowed to split my if statement even when I'm not splitting the block with indentation for obvious python-reasons. I'm a total newbie in regard of python so I'm sorry if my question is annoying.

Ideally, I would like to have the if statement arranged this way:

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

Right now it's all in one line and not a lot of readable.

Ditto
  • 296
  • 1
  • 13

4 Answers4

3

You could use old-style backslashing for the first line, others don't need it because you're using parentheses:

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

note that your example had to be fixed because there was one closing parenthesis missing.

Jean-François Fabre
  • 137,073
  • 23
  • 153
  • 219
1

Use a \ to have your expression on multiple lines, you can even ident it for more readability:

if (expression1 and expression2) or \
(expression2 and \
    (\
    (expression3 and expression4) or \
    (expression3 and expression5) or \
        ( \
         expression4 and (expression6 or expression7) \
         )\
         ):
    pass
LoicM
  • 1,786
  • 16
  • 37
1

Python has several ways to allow multi-line statements. In your case, you can simple wrap your entire if condition in parenthesis:

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

I should note however, having that many conditions in a single if statement seems like a bit of a code smell to me. Perhaps consider create helper functions to incapsulate some of the logic, or using multiple if statements.

Christian Dean
  • 22,138
  • 7
  • 54
  • 87
0

you could do this:

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
mikeLundquist
  • 769
  • 1
  • 12
  • 26