How to comment each condition in a multi-line if statement in Python?

PythonProgramming

You can do this directly if you are surrounding your multiline if statements conditions in a parenthesis. For example,

if (cond1 == 'val1' and
   cond2 == 'val2' and # Some comment
   cond3 == 'val3' and # Some comment
   cond4 == 'val4'):

However, this is not possible if you try to do this without a parenthesis. For example, the following code will give an error:

if cond1 == 'val1' and \
   cond2 == 'val2' and \ # Some comment
   cond3 == 'val3' and \ # Some comment
   cond4 == 'val4':
raja
Published on 19-Apr-2018 16:39:18
Advertisements