Module 16 · Lesson 03
Assertions and Defensive Programming
State your code's assumptions with assert, validate outside input with real exceptions, fail fast with guard clauses, protect shared data with defensive copies, and know why asserts must never guard user input.
- About 10 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- assert your assumptions
- Validate input with real exceptions
- Guard clauses first
- Watch the guards at work
Catch mistakes early
Defensive code checks its assumptions and refuses bad data before it can do damage.
assert
assert total >= 0, "negative total"stops the program if your own logic is wrong.Real exceptions
Check outside input with
ifandraise ValueError. Those checks always run.Guard clauses
Handle the bad cases first and return early, so the main path stays flat.
Defensive copies
Copy a list you were given before keeping it, so outside changes cannot reach in.
Defensive code everywhere
Systems that must not fail check everything at the door.
- BankingA transfer refuses a negative amount before any money moves.
- Sign-up formsReject an empty email address before saving anything.
- SensorsCheck that every reading is in a sensible range before acting on it.
- Tests
assert add(2, 2) == 4is how many test tools check results.
Reading an assert
This line states something that must be true if the code is correct. Tap each part to see its job.
Part 1 of 4
assert:Checks a condition. If it is False, Python raises AssertionError.
Check before you trust
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6assert in action
The assert states what average needs. It stays silent while that holds.
Your turn: Call average([]) on a new line and read the message.
def average(nums):
assert len(nums) > 0, "average needs at least one number"
return sum(nums) / len(nums)
print(average([4, 8, 6]))
print(average([10]))Press Run to see what it prints.Watch the guards at work
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- def withdraw(balance, amount):
- if amount <= 0:
- raise ValueError("amount must be positive")
- if amount > balance:
- return balance, "refused"
- new = balance - amount
- assert new >= 0
- return new, "ok"
- print(withdraw(50, 20))
- print(withdraw(50, 80))
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.A copy of a list of lists:
a = [[1], [2]]
b = list(a)
b[0].append(9)
print(a)0 of 6 answered
Common defensive coding misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
assert condition # AssertionError if False
assert condition, "message" # with a message
python -O script.py # removes all asserts!
if value < 0: # validate input: always runs
raise ValueError(f"... {value}")
if not isinstance(x, int):
raise TypeError("x must be an int")
def f(x): # guard clauses
if bad1:
return ... # or raise
if bad2:
raise ValueError(...)
return main_work(x)
items = list(items) # defensive copy before changing
return tuple(self._items) # hand out a read-only viewPress Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
A discount function with guard clauses
Write discounted(price, percent) that rejects wrong types and impossible values with clear exceptions, then asserts its own result is sensible before returning it.
def discounted(price, percent):
if not isinstance(price, (int, float)) or isinstance(price, bool):
raise TypeError(f"price must be a number, got {type(price).__name__}")
if price < 0:
raise ValueError(f"price cannot be negative, got {price}")
if not 0 <= percent <= 100:
raise ValueError(f"percent must be 0 to 100, got {percent}")
result = round(price * (100 - percent) / 100, 2)
assert 0 <= result <= price, "a discount can never raise the price"
return result
print(discounted(80, 25))
print(discounted(19.99, 0))
for bad in [("80", 10), (-5, 10), (50, 120)]:
try:
discounted(*bad)
except (TypeError, ValueError) as error:
print(type(error).__name__ + ":", error)Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
Validating user input with assert
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
def withdraw(balance, amount):
assert amount > 0, 'amount must be positive'
return balance - amount
# run with: python -O bank.py
print(withdraw(100, -50))Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Logistics
Reserving warehouse stock safely
A warehouse system reserves stock for incoming orders from several shop websites. Orders are outside data and are checked with exceptions. The stock table is internal, so its invariant (no item ever goes below zero) is asserted. Orders are checked completely before any stock changes, so a bad line never leaves an order half reserved.
Why Python fits
All checks run before the first change, so the second order, which fails on its lamp line, leaves the mugs untouched too. Each rejection names the exact problem. The assert at the end is not input validation: it can only fail if the reserving code itself is wrong, which is precisely what an assertion is for.
Pythonclass OrderError(Exception): pass stock = {"mug": 10, "lamp": 2, "rug": 0} def reserve(order_lines): lines = [(item, qty) for item, qty in order_lines] # defensive copy if not lines: raise OrderError("order has no lines") for item, qty in lines: if item not in stock: raise OrderError(f"unknown item {item!r}") if not isinstance(qty, int) or qty <= 0: raise OrderError(f"bad quantity {qty!r} for {item}") if qty > stock[item]: raise OrderError(f"only {stock[item]} {item} left") for item, qty in lines: stock[item] -= qty assert all(count >= 0 for count in stock.values()), "stock went negative" return f"reserved {sum(qty for _, qty in lines)} items" orders = [ [("mug", 3), ("lamp", 1)], [("mug", 2), ("lamp", 5)], [("vase", 1)], [("mug", "2")], [], ] for order in orders: try: print(reserve(order)) except OrderError as error: print("rejected:", error) print("stock now:", stock)OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
How many asserts should I write?
Does anyone really run Python with -O?
Should I check every argument's type?
Is raising an exception better than returning None for bad input?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 15 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.