Assertions
Assertions
Sometimes you want to check that something must be true.
If it is false, the program should stop and show an error.
Python gives us assert for this.
What Is an Assertion?
An assertion is a quick check.
If the condition is True, the program continues.
If the condition is False, Python raises an error.
Basic Structure
assert condition
Or with a message:
assert condition, "message"
Why Assertions Matter
Assertions help you:
- Catch bugs early
- Check assumptions
- Test code while building
- Find wrong values quickly
Example: Positive Number
number = 5
assert number > 0
print("Valid")
Output
Valid
Example: Failing Assertion
number = -1
assert number > 0, "Number must be positive"
Result
Python shows:
AssertionError: Number must be positive
Example: Function Check
def divide(a, b):
assert b != 0, "Cannot divide by zero"
return a / b
print(divide(10, 2))
Output
5.0
Example: String Check
name = "Tom"
assert name != "", "Name cannot be empty"
print("Saved")
Output
Saved
Assertions vs if
Use if when handling user choices.
Use assert when checking something that should always be true during development.
Good Uses of Assertions
- Value should not be empty
- Number should be positive
- List should have items
- Function input should be valid
Code Along
Build a score checker.
Rules:
- Score must be 0 to 100
Use assert.
Mini Challenge
Build a stock checker.
Steps:
- Create:
stock = 5
- Use
assertto check stock is greater than0 - Print:
In stock
Expected output:
In stock
Real World Use Case
Developers use assertions while testing code, checking values, and finding bugs faster.
Quiz
- What does
assertdo? - What error happens when an assertion fails?
- When should you use assertions?
- Can assertions have messages?
Assignment
Create a program that stores an age and uses assert to make sure age is 18 or more.
Summary
You learned how assertions check conditions and help catch bugs during development.