πŸ”₯ Welcome to my blog! Latest updates available now. Visit daily! πŸ”₯ πŸ”₯ Click Here for Latest Updates – Visit My Blog πŸ”₯
πŸ”₯ Latest Updates πŸ“Š GP Grade Finder πŸ“’ Government Services Info πŸ†• New Schemes Updates

Assert Statements in Python

 1. Simple Version:

assert conditional_expression

2. Augmented Version:

assert conditional_expression, message

conditional_expression will be evaluated and if it is true then the program will be continued.

If it is false then the program will be terminated by raising AssertionError.

By seeing AssertionError, programmer can analyze the code and can fix the problem.

Example

def squareIt(x):

   return x * x

assert squareIt(2) == 4, "The square of 2 should be 4"

assert squareIt(3) == 9, "The square of 3 should be 9"

assert squareIt(4) == 16, "The square of 4 should be 16"

print(squareIt(2))

print(Square(3))

print(squareIt(4))


D:\Python3>py test.py

Traceback (most recent call last):

File "test.py", line 4, in <module>

assert squareIt(3) == 9, "The square of 3 should be 9"

AssertionError: The square of 3 should be 9


def squareIt(x):

    return x * x

 assert squareIt(2) == 4, "The square of 2 should be 4"

assert squareIt(3) == 9, "The square of 3 should be 9"

assert squareIt(4) == 16, "The square of 4 should be 16"

print(squareIt(2))

print(squareIt(3))

print(squareIt(4))


Output

 4

9

16


Exception Handling vs Assertions:

Assertions concept can be used to alert programmer to resolve development time errors.

Exception Handling can be used to handle runtime errors.

No comments:

Post a Comment

Thank you Very Much.For Given Comment

Quatation of the Day 22-03-2026