Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 252
turbulencetoo Avatar asked Apr 07 '14 14:04

turbulencetoo


People also ask

How do you comment on multiple lines?

To comment out multiple lines in Python, you can prepend each line with a hash ( # ). With this approach, you're technically making multiple single-line comments. The real workaround for making multi-line comments in Python is by using docstrings.

How do you check multiple items in an if statement?

Here we'll study how can we check multiple conditions in a single if statement. This can be done by using 'and' or 'or' or BOTH in a single statement. and comparison = for this to work normally both conditions provided with should be true. If the first condition falls false, the compiler doesn't check the second one.

How will you describe multi-line comment?

Multiline comments are used for large text descriptions of code or to comment out chunks of code while debugging applications. Comments are ignored by the compiler.

Can you write more than one condition in one if statement?

Use two if statements if both if statement conditions could be true at the same time. In this example, both conditions can be true. You can pass and do great at the same time. Use an if/else statement if the two conditions are mutually exclusive meaning if one condition is true the other condition must be false.


1 Answers

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!
like image 189
Martijn Pieters Avatar answered Sep 29 '22 15:09

Martijn Pieters