Sometimes I break long conditions in if
s onto several lines. The most obvious way to do this is:
if (cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something
Isn't very very appealing visually, because the action blends with the conditions. However, it is the natural way using correct Python indentation of 4 spaces.
For the moment I'm using:
if ( cond1 == 'val1' and cond2 == 'val2' and cond3 == 'val3' and cond4 == 'val4'): do_something
But this isn't very pretty. :-)
Can you recommend an alternative way?
When you combine each one of them with an IF statement, they read like this: AND – =IF(AND(Something is True, Something else is True), Value if True, Value if False) OR – =IF(OR(Something is True, Something else is True), Value if True, Value if False) NOT – =IF(NOT(Something is True), Value if True, Value if False)
In Python, I prefer to use vertical space, enclose parenthesis, and place the logical operators at the beginning of each line so the expressions don't look like "floating". If the conditions need to be evaluated more than once, as in a while loop, then using a local function is best.
You can add multiple conditions using either “and” and/or “or” operators. That means it is && or ||. If we are using && then the if statement will be executed if both the conditions are true and in case of || then the if statement will be executed if either of those conditions is true.
nested-if in C/C++ Nested if statements mean an if statement inside another if statement. Yes, both C and C++ allow us to nested if statements within if statements, i.e, we can place an if statement inside another if statement.
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.
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