Fix: AssertionError in Python

AssertionError is a built-in concrete exception in Python that is raised when an assert statement fails.



What are assert statements?

    Assert statements are used to debug assertions into a program.

    Syntax:

    assert_stmt ::= "assert" expression ["," expression]

    Example:
    age = 13
    
    assert age > 18, "Age should be greater than 18"
    Traceback:
    % python3 example.py
    
    Traceback (most recent call last):
      File "/Users/c2ctechtv/Desktop/example.py", line 2, in <module>
        assert age > 18, "Age should be greater than 18"
               ^^^^^^^^
    AssertionError: Age should be greater than 18
    Python AssertionError Example

As you can see from the above example when the condition specified in the assert statement evaluates to False an AssertionError is raised.



Fix and Conclusion:

    assert statements are mostly used during development and testing to catch issues and make sure that your code behaves as expected. It could be valid for an assertion to fail as per test cases so there could be nothing to fix as well.



Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!