Question

I want to have a multi-line if statement such as:

if CONDITION1 or\
   CONDITION2 or\
   CONDITION3:

I want to comment the end of each line of source code

if CONDITION1 or\ #condition1 is really cool
   CONDITION2 or\ #be careful of condition2!
   CONDITION3:    #see document A sec. B for info

I am prohibted from doing this because python sees it all as one line of code and reports SyntaxError: unexpected character after line continuation character.

How should I go about implementing and documenting a long, multi-line if statement?

Was it helpful?

Solution

Don't use \, use parenthesis:

if (CONDITION1 or
    CONDITION2 or
    CONDITION3):

and you can add comments at will:

if (CONDITION1 or  # condition1 is really cool
    CONDITION2 or  # be careful of conditon2!
    CONDITION3):   # see document A sec. B for info

Python allows for newlines in a parenthesised expression, and when using comments that newline is seen as being located just before the comment start, as far as the expression is concerned.

Demo:

>>> CONDITION1 = CONDITION2 = CONDITION3 = True
>>> if (CONDITION1 or  # condition1 is really cool
...     CONDITION2 or  # be careful of conditon2!
...     CONDITION3):   # see document A sec. B for info
...     print('Yeah!')
... 
Yeah!
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top