14k 26
Top 1% !
Pearl of Wisdom
Popularity: 1170th place
Modified May 5, 2014

Published on:


Avoid complicated 'if' statements

The Bad, Ugly Villain and the Good, Handsome Hero
Copy Embed Code
<iframe id="embedFrame" style="width:600px; height:300px;"
Click on the embed code to copy it into your clipboard Width Height
Leave empty to retrieve all the content Start End
def decide_in_the_wrong_way(a, b, c): """ return True if one of the conditions holds true using a bunch of complicated, messy if statements, multiple exit points """ if a < 12 and b*c > 80: return True if a >= 12 and b*c/a > 20: return True if a < 0: return True else: if 10 <= b*c <= 15: return True else: return False # ... and a bunch of other conditions.. return False def decide_in_the_right_way(a, b, c): """ return True if one of the conditions holds true using innner functions which express the conditions in in an easily understandable form """ def decision1(a, b, c): return a < 12 and b*c > 80 def decision2(a, b, c): return 12 and b*c/a > 20 def decision3(a, b, c): def sensibly_named_condition(b, c): return 10 <= b*c <= 15 return a < 0 or sensibly_named_condition(b,c) # ... and a bunch of other similar boolean functions.. # collect the decision functions in a list decisions = [decision_fv for name, decision_fv in locals().items() if name.startswith("decision")] # note the use of "for ... else"! for decision in decisions: result = decision(a, b, c) if result: break else: result = False # executed only if no "break" occurred in the loop return result # note that the function has a single exit point if __name__ == "__main__": if decide_in_the_wrong_way(12,21,8): print "YES! - in the wrong way" else: print "No! - in the wrong way" if decide_in_the_right_way(12,21,8): print "YES! - in the right way" else: print "No! - in the right way"
If you want to be updated about similar snippets, Sign in and follow our Channels

blog comments powered by Disqus