vendredi 9 novembre 2018

Python: if not or statement vs nested if statement

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.

Aucun commentaire:

Enregistrer un commentaire