Read Code Fast

Lesson 20 Edge cases

6 min read · Python · Quiz

empty input, off-by-one, money in floats, time zones, Unicode, falsy zero

What you'll learn

  • Test every function against empty, one, zero and huge input
  • Recognise the traps in money, time zones and text
  • Predict where a happy-path function breaks

The AI tested the code with one friendly example, and it worked. Real users bring empty carts, zero quantities and names with accents.

The idea

AI writes for the happy path: a normal user with a normal cart. The bugs live at the edges. Ask the same few questions of every function: what if it's empty? what if there is one item? what if it's zero or negative? what if it's huge?

Some inputs are traps in themselves: money as decimal numbers, dates without a time zone, text with emoji and accents, and zero treated as "nothing". You don't need to run the code in your head. Pick the nastiest input and see where the lines break.

invoice_summary.py
1def invoice_summary(lines):2    total = 0.03    for line in lines:4        total += line["price"] * line["qty"]5    tax = total * 0.08256    biggest = max(line["price"] for line in lines)7    average = total / len(lines)8    return {"total": total + tax, "biggest": biggest, "average": average}
  1. Line 3 On an empty list the loop just doesn't run: this part is safe. total stays 0.0.
  2. Line 5 Money as float. Float arithmetic has tiny errors. Use Decimal("0.0825") built from text, or whole cents.
  3. Line 6 max of nothing raises ValueError. The empty cart crashes here, before the next line.
  4. Line 7 With no lines this is a ZeroDivisionError. An average is a classic empty-input trap.

Take away

  • Test every function with the empty, the one, the zero and the huge.
  • Money belongs in whole cents or Decimal built from text, never in float dollars.
  • Dates need a time zone and text needs a second look: accents can be spelled two ways.

Quiz: test yourself

7 questions: a quick quiz, then a review drill. Pick an answer to see why it's right.