Reputation: 545
I'm having a very hard time wrapping my head around if not or statements. Thanks to stackoverflow, I'm aware the the expression proceeding the or statement will only execute if the first if not statement is False, but all my fingers seem to want to type when confronted with a possible use case of this, is rather a nested if statement.
For example, the following classes are producing the same output for whatever x is.
def if_not_or(self, x):
if not isinstance(x, int) or x % 2 == 0:
return False
return True
def nested_if(self, x):
if isinstance(x, int):
if x % 2 == 1:
return True
return False
Even though the first method clearly appears to be more elegant, does it offer any particular advantage over the ladder method? I fear that if a potential use case for this appears within one of my projects, I'll simply opt for the nested if approach because it's easier for me to wrap my beginner-intermediate programming mind around. Thanks very much for any enlightenment on the topic.
Upvotes: 1
Views: 188
Reputation: 528
There is a third approach to your problem, that is:
def direct_return(self, x):
# return True if x is an odd number, False otherwise
return isinstance(x, int) and x % 2 == 1
With any of these approaches you will see a performance difference. But as suggested in comments, readability counts.
Upvotes: 1