Styling Multi-Line Conditions in 'If' Statements

Styling multi-line conditions in 'if' statements?

You don't need to use 4 spaces on your second conditional line. Maybe use:

if (cond1 == 'val1' and cond2 == 'val2' and 
cond3 == 'val3' and cond4 == 'val4'):
do_something

Also, don't forget the whitespace is more flexible than you might think:

if (   
cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'
):
do_something
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something

Both of those are fairly ugly though.

Maybe lose the brackets (the Style Guide discourages this though)?

if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and cond4 == 'val4':
do_something

This at least gives you some differentiation.

Or even:

if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_something

I think I prefer:

if cond1 == 'val1' and \
cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_something

Here's the Style Guide, which (since 2010) recommends using brackets.

Good C-coding style for multiple lines if conditions

If you want to stick with your existing code (as opposed to factor things out into inline functions), and just modify the indentation, I'm a big fan of using indent consistently. This means you can fix any source file.

With its default options it gives you GNU indentation, i.e.:

if (((g_cycle_cnt == uartTxSecondaryMsg[3][msgPos[3]].sliceNo) ||       //correct slicenumber...
(uartTxSecondaryMsg[3][msgPos[3]].sliceNo == -1) || // or as fast as possible...
((uartTxSecondaryMsg[3][msgPos[3]].sliceNo == -2) &&
((uartTxSecondaryMsg[3][msgPos[3]].timeFrameBegin >= g_uptime_cnt) &&
(uartTxSecondaryMsg[3][msgPos[3]].timeFrameEnd <= g_uptime_cnt)))) &&
((dataProcessingFlag & SECONDARY_MSG_ANNOUNCED_CH4) ==
SECONDARY_MSG_ANNOUNCED_CH4))
{
/* do something */
}

I'd say that the problem here is in fact that you are poking about illegibly in arrays. At the very least, factor out:

uartTxSecondaryMsg[3][msgPos[3]]

into a separate variable, e.g.:

whatever *foo = &uartTxSecondaryMsg[3][msgPos[3]];
if (((g_cycle_cnt == foo->sliceNo) || //correct slicenumber...
(foo->sliceNo == -1) || // or as fast as possible...
((foo->sliceNo == -2) &&
((foo->timeFrameBegin >= g_uptime_cnt) &&
(foo->timeFrameEnd <= g_uptime_cnt)))) &&
((dataProcessingFlag & SECONDARY_MSG_ANNOUNCED_CH4) ==
SECONDARY_MSG_ANNOUNCED_CH4))
{
/* do something */
}

Obviously choose an appropriate type and variable name for foo.

You could then separate out the limbs of the if statement into separate functions each taking foo as a parameter.

Multiline If statement with a single conditional

Firstly, PEP 8 says you can split long lines under Maximum Line Length:

Long lines can be broken over multiple lines by wrapping expressions in parentheses. These should be used in preference to using a backslash for line continuation.

In fact, the backslash in your example is not needed because of the parentheses.


PEP 8 says you can split a conditional under multiline if-statements, although the main focus of that section is how to distinguish it from the following block.

When the conditional part of an if-statement is long enough to require that it be written across multiple lines, it's worth noting that the combination of a two character keyword (i.e. if), plus a single space, plus an opening parenthesis creates a natural 4-space indent for the subsequent lines of the multiline conditional. This can produce a visual conflict with the indented suite of code nested inside the if-statement, which would also naturally be indented to 4 spaces. This PEP takes no explicit position on how (or whether) to further visually distinguish such conditional lines from the nested suite inside the if-statement. Acceptable options in this situation include, but are not limited to:

# No extra indentation.
if (this_is_one_thing and
that_is_another_thing):
do_something()

# Add a comment, which will provide some distinction in editors
# supporting syntax highlighting.
if (this_is_one_thing and
that_is_another_thing):
# Since both conditions are true, we can frobnicate.
do_something()

# Add some extra indentation on the conditional continuation line.
if (this_is_one_thing
and that_is_another_thing):
do_something()

Personally, I would go for the last option for maximum readability. So that gives us:

if (self.SuperLongSpecificCorperateVariableNameIcantChangeCommunication
!= self.SuperLongSpecificCorperateVariableNameIcantChangeControl):
do_something()

Other options

You could use temporary "internal use" names to shorten the line:

_Comm = self.SuperLongSpecificCorperateVariableNameIcantChangeCommunication
_Control = self.SuperLongSpecificCorperateVariableNameIcantChangeControl
if _Comm != _Control:
do_something()

This is assuming the context is not in a local scope. If it is actually in a local scope, they don't need to be "internal use".


You could use a helper function to give them shorter names in a local scope. Since they're attributes, you can pass in their object:

def _compare(instance):
a = instance.SuperLongSpecificCorperateVariableNameIcantChangeCommunication
b = instance.SuperLongSpecificCorperateVariableNameIcantChangeControl
return a != b

if _compare(self):
do_something()

Code-style for indention of multi-line 'if' statement?

This is an indirect answer--not answering the style question directly, but it's the practical answer in general, so it's worth mentioning.

I find it extremely rare to need to write multi-line conditionals. There are two factors to this:

  • Don't wrap code at 80 columns. PEP-8's advice on this subject is ancient and harmful; we're well past the days of 80x25 terminals and editors that can't sensibly handle wrapping. 100 columns is fine, and 120 is usually acceptable, too.
  • If conditions become so long that they still need to wrap, it's usually reasonable to move some of the logic out of the conditional and into a separate expression. This also tends to help readability.

Grepping through my recent projects, around 12kloc, there's only one conditional long enough that it needed to be wrapped; the issue simply very rarely arises. If you do need to do this, then as nosklo says, indent it separately--as you noticed, indenting it to the same level as the block beneath it is confusing and hard to read.

What's the proper way to format if statements in Java with multiline ands or ors?

The Oracle/Sun guidelines ("Code Conventions for the Java TM Programming Language") tell us to break before an operator. And they give this example.

if ((condition1 && condition2)
|| (condition3 && condition4)
||!(condition5 && condition6)) {
doSomethingAboutIt();
}

Many companies that I've worked for adopt the Oracle/Sun guidelines as the standard for their own code.

Refer http://www.oracle.com/technetwork/java/javase/documentation/codeconventions-136091.html#248

Very Long If Statement in Python

According to PEP8, long lines should be placed in parentheses. When using parentheses, the lines can be broken up without using backslashes. You should also try to put the line break after boolean operators.

Further to this, if you're using a code style check such as pycodestyle, the next logical line needs to have different indentation to your code block.

For example:

if (abcdefghijklmnopqrstuvwxyz > some_other_long_identifier and
here_is_another_long_identifier != and_finally_another_long_name):
# ... your code here ...
pass

How to have multiple conditions for one if statement in python

I would use

def example(arg1, arg2, arg3):
if arg1 == 1 and arg2 == 2 and arg3 == 3:
print("Example Text")

The and operator is identical to the logic gate with the same name; it will return 1 if and only if all of the inputs are 1. You can also use or operator if you want that logic gate.

EDIT: Actually, the code provided in your post works fine with me. I don't see any problems with that. I think that this might be a problem with your Python, not the actual language.



Related Topics



Leave a reply



Submit