In computer programming, a guard is a boolean expression that must evaluate to true if the program execution is to continue in the branch in question (more here). They can replace the nested if-else statements for example, acting like the security guards: you can go through in a function only if you pass the conditions, otherwise just leave.
Some nested if-else statements could be like:
def analyzeInput(input): if i >= 0: if i <= 10: print "Do the calculation..." else: print "ERROR:The number should be less than 10" else: print "ERROR The number shouldn't be over 0" print "ERROR MSG: %s" % error i = int(raw_input("Provide a number please between 1-10 ")) print i analyzeInput(i)
Using guards, the function can be transformed into:
# refactoring the code using guards def analyzeInputRef(input): if i < 0: print "ERROR:The number shouldn't be over 0" return if i > 10: print "ERROR:The number should be less than 10" return print "Do the calculation..."