assert
KeywordPython 2.0+Intermediate
Debugging aid that tests a condition and raises AssertionError if false
Quick Info
- Documentation
- Official Docs
- Python Version
- 2.0+
Learn by Difficulty
Quick Example
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}")
assert checks a condition and raises AssertionError if it's False. The message after the comma is optional but recommended.
Try in PlaygroundTags
languagesyntaxcoredebuggingtesting