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?
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.
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.
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.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With