CodingNic

Error Handling and Debugging

Assertions

Error Handling and Debugging 24 min read

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

python
assert condition

Or with a message:

python
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

python
number = 5
assert number > 0
print("Valid")

Output

text
Valid

Example: Failing Assertion

python
number = -1
assert number > 0, "Number must be positive"

Result

Python shows:

text
AssertionError: Number must be positive

Example: Function Check

python
def divide(a, b):
    assert b != 0, "Cannot divide by zero"
    return a / b

print(divide(10, 2))

Output

text
5.0

Example: String Check

python
name = "Tom"
assert name != "", "Name cannot be empty"

print("Saved")

Output

text
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:
python
stock = 5
  • Use assert to check stock is greater than 0
  • Print:
text
In stock

Expected output:

text
In stock

Real World Use Case

Developers use assertions while testing code, checking values, and finding bugs faster.

Quiz

  1. What does assert do?
  2. What error happens when an assertion fails?
  3. When should you use assertions?
  4. 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.