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


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':

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 17-Jun-2020

166 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements