assert — Easy Examples
Debugging aid that tests a condition and raises AssertionError if false
Basic assertions
Using assert to verify conditions during development.
python
x = 10 assert x > 0, "x must be positive" print("x is valid") # Assert with expressions name = "Alice" assert len(name) > 0, "Name cannot be empty" print(f"Name: {name}") # Catching assertion errors try: temperature = -300 assert temperature > -273.15, f"Temperature {temperature} is below absolute zero" except AssertionError as e: print(f"Invalid: {e}")
Expected Output
x is valid Name: Alice Invalid: Temperature -300 is below absolute zero
assert checks a condition and raises AssertionError if it's False. The message after the comma is optional but recommended.
Want to try these examples interactively?
Open Easy Playground