python · level 2 · unit 4 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
checks a fact and complains loudly if it is false.
assert is followed by a condition. If the condition is True, nothing happens and the program carries on. If it is False, Python stops with an : an error you planned on purpose.
That makes assert perfect for a . Call your function with a value whose answer you already know, and assert the result. A wrong answer is caught now, not in front of a customer.
Add a message after a comma, and it is shown when the check fails.
def add_vat(price):
return price * 1.2
assert add_vat(10) == 12, "10 plus VAT should be 12"
assert add_vat(0) == 0, "0 plus VAT should be 0"
print("All tests passed") Tests are code that checks code, and professional programmers write them every day.
guess first
Testing a half-price sale. What will this show?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
def half_price(price):
return price / 2
assert half_price(10) == 5, "10 should halve to 5"
print("First test passed")
assert half_price(5) == 2, "5 should halve to 2"
print("Second test passed")
your turn
Your turn. Test a temperature converter.
Water freezes at 0 °C, which is 32 °F, and boils at 100 °C, which is 212 °F. And -40 is the one temperature that is the same in both. Fill in each answer, then run your tests.
fix it
A test says the shop maths is wrong. Fix the function!
- Read the message after AssertionError. Which test failed, and what answer did it expect?
- The test is right: 3 items at 2 cost 6. The function adds the numbers when it should multiply them.
- Change + to * on line 2, then run.
nailed it
your code now checks itself. :D
assertstays quiet when true and stops when false.- A test calls a function with a known answer and asserts it.
- When a correct test fails, fix the code, not the test.
new words in your collection
- assert
- AssertionError
- test
This lesson isn’t saved. A free account remembers every lesson you finish.