lundi 22 juin 2015

How to make nested IF statements neater

This question could be asked in a language independent way but I'm asking in the context of python since different languages will have different nuances.

I recognize that this is similar to this question but I think mine is different in that I'm asking about a case where putting the two conditions in the same if statement with & will generate an error.

Let's say I want to see if abc[x] is equal to 'fish' but let's say I don't know for sure that len(abc) is >= to x. I can't just have if abc[x]=='fish' because it might be index out of range. As such I need to do

if len(abc)>=x:
    if abc[x]=='fish':
        dostuff
    else:
        dootherstuff
else:
    dootherstuff

Is there a cleaner way to do this where I don't have two else statements that end up doing the same dootherstuff? If I want to change what dootherstuff is later than I have to change it in both places but by then I might forget. Sure I could try to comment the code to remind myself later or make dootherstuff a function but that still seems second best. A lot of times when I wind up doing this the dootherstuff is just a one line of code so making it a function doesn't feel much better even though it addresses the subsequent change scenario.

Aucun commentaire:

Enregistrer un commentaire