Lessons · Python · returning True/False
Returning the answer, not a description of it
A comparison already IS a True or False; return it directly instead of wrapping it in if/else.
Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.
What it is for
Functions that answer yes/no questions are everywhere: is_valid, is_empty, can_afford. Writing them cleanly makes the calling code read like English.
How to think about it
Is the condition already the answer? If you find yourself writing 'if condition: return True else: return False', delete everything except 'return condition'.
Worked example
def is_adult(age):A yes/no question.
return age >= 18age >= 18 evaluates to True or False. That is the answer; return it.
print(is_adult(20), is_adult(12))True False.
Your turn
Return whether a list is empty, in one line.
def is_empty(items):
return len(items) 0Solve one with the tests running
The trap
Returning the strings 'True' and 'False'. They are text, always truthy, and the caller's if will never take the else branch.
Practise returning True/False on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.