Table of Contents

Understanding Python’s Assert Statement

Example Description
Learn how to use Python's assert statement with this program. See its implementation through a function that checks for negative numbers and raises an error if the condition is not met.

Introduction:

In Python, the assert statement is a powerful debugging tool used to check if a condition is true during the execution of a program. It allows you to catch errors early by validating assumptions and helps in debugging the code effectively. In this tutorial, we’ll explore the practical use of the assert statement by creating a function that checks for negative numbers and raises an error with a custom message if the condition is not met.

Code:

print("use of assert statement")
def negativecheck(number):
  assert(number>=0), "OOPS... Negative Number"
  print(number*number)
print(negativecheck(100))
print(negativecheck(-350))

Logic:

  1. The first line is a simple print statement that displays the text “use of assert statement.”
  2. The function negativecheck(100) is called with the argument 100. The assert statement in this case passes since 100 is greater than or equal to zero.
  3. The function proceeds to calculate the square of 100 (100 * 100) and prints the result: 10000.
  4. Next, the function negativecheck(350) is called with the argument -350. The assert statement fails because -350 is not greater than or equal to zero.
  5. As a result, the AssertionError is raised, and the custom error message “OOPS… Negative Number” is displayed.

Output:

 >>use of assert statement

>>10000

>>None

Traceback (most recent call last):

    File “<file_name>”, line 6, in <module>

        print(negativecheck(-350))

  File “<file_name>”, line 4, in negativecheck

      assert(number>=0), “OOPS… Negative Number”

AssertionError: OOPS… Negative Number