Lessons · Python · leave as soon as you know
Leave as soon as you know
return ends the function immediately. Returning early for the simple cases keeps the main path unindented and clear.
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
Deeply nested if/else is where bugs hide. Handling the edge cases first and returning makes the rest of the function read top to bottom.
How to think about it
Ask: what inputs have an obvious answer? Empty, None, zero, already done. Check those first, return, and write the real logic for the rest without an else.
Worked example
def first_word(text):First word of a sentence, or empty text.
if not text:The simple case.
return ""Answered; gone.
return text.split()[0]The real case, not indented inside an else.
Your turn
Return 0 immediately for an empty list.
def average(xs):
if not xs:
0
return sum(xs) / len(xs)Solve one with the tests running
The trap
Code after a return in the same block never runs. If you see it, it is dead.
Practise leave as soon as you know on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.