Lesson 5
Writing Reusable and Self-explanatory Programs
Chapter 4: Refactoring
Returning booleans
Here is another tip 💡
Note how I wrote the is_divisible_by()
function earlier. It is pretty compact.
# Recommended
def is_divisible_by(number, divisor):
return number % divisor == 0
Compare that to the second version below.
# Not recommended: Too verbose
def is_divisible_by(number, divisor):
if number % divisor == 0:
return True
else:
return False
If you read this second version, it says “if the condition is True, return True; else return False”. This is quite verbose and redundant. Why not just say “return the condition” (which could be either True or False)?
So rather than wasting time checking whether a boolean expression is True
and then returning True
, it is more concise to just return the boolean expression itself (which is already either True
or False
)! It is shorter and more efficient (Python does not need to do the check with the if
statement).
Note that this function returns a bool
. Such functions are useful for checking whether the input argument(s) fulfil a certain condition. It is quite a good convention to name such functions something like is_divisible()
or has_property()
to indicate that it is a boolean function.
Also notice that I tend to name functions as verb phrases. It just makes your code easier to read!