Python assert keyword Syntax

In Python, the assert keyword helps in achieving this task. This statement takes as input a boolean condition, which when returns true doesn’t do anything and continues the normal flow of execution, but if it is computed to be false, then it raises an AssertionError along with the optional message provided. 

Syntax : assert condition, error_message(optional) 

Parameters:

  • condition : The boolean condition returning true or false. 
  • error_message : The optional argument to be printed in console in case of AssertionError

Returns: Returns AssertionError, in case the condition evaluates to false along with the error message which when provided. 

Python assert keyword without error message

This code is trying to demonstrate the use of assert in Python by checking whether the value of b is 0 before performing a division operation. a is initialized to the value 4, and b is initialized to the value 0. The program prints the message “The value of a / b is: “.The assert statement checks whether b is not equal to 0. Since b is 0, the assert statement fails and raises an AssertionError.
Since an exception is raised by the failed assert statement, the program terminates and does not continue to execute the print statement on the next line.

Python3




# initializing number
a = 4
b = 0
 
# using assert to check for 0
print("The value of a / b is : ")
assert b != 0
print(a / b)


Output:

The value of a / b is : 
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
Input In [19], in <cell line: 10>()
      8 # using assert to check for 0
      9 print("The value of a / b is : ")
---> 10 assert b != 0
     11 print(a / b)

AssertionError: 

Python assert keyword with an error message

This code is trying to demonstrate the use of assert in Python by checking whether the value of b is 0 before performing a division operation. a is initialized to the value 4, and b is initialized to the value 0. The program prints the message “The value of a / b is: “.The assert statement checks whether b is not equal to 0. Since b is 0, the assert statement fails and raises an AssertionError with the message “Zero Division Error”.
Since an exception is raised by the failed assert statement, the program terminates and does not continue to execute the print statement on the next line.

Python3




# Python 3 code to demonstrate
# working of assert
 
# initializing number
a = 4
b = 0
 
# using assert to check for 0
print("The value of a / b is : ")
assert b != 0, "Zero Division Error"
print(a / b)


Output:

AssertionError: Zero Division Error

Assert Inside a Function

The assert statement is used inside a function in this example to verify that a rectangle’s length and width are positive before computing its area. The assertion raises an AssertionError with the message “Length and width must be positive” if it is false. If the assertion is true, the function returns the rectangle’s area; if it is false, it exits with an error. To show how to utilize assert in various situations, the function is called twice, once with positive inputs and once with negative inputs.

Python3




# Function to calculate the area of a rectangle
def calculate_rectangle_area(length, width):
    # Assertion to check that the length and width are positive
    assert length > 0 and width > 0, "Length and width"+ \
                "must be positive"
    # Calculation of the area
    area = length * width
    # Return statement
    return area
 
 
# Calling the function with positive inputs
area1 = calculate_rectangle_area(5, 6)
print("Area of rectangle with length 5 and width 6 is", area1)
 
# Calling the function with negative inputs
area2 = calculate_rectangle_area(-5, 6)
print("Area of rectangle with length -5 and width 6 is", area2)


Output:

AssertionError: Length and widthmust be positive

Assert with boolean Condition

In this example, the assert statement checks whether the boolean condition x < y is true. If the assertion fails, it raises an AssertionError. If the assertion passes, the program continues and prints the values of x and y.

Python3




# Initializing variables
x = 10
y = 20
 
# Asserting a boolean condition
assert x < y
 
# Printing the values of x and y
print("x =", x)
print("y =", y)


Output:

x = 10
y = 20

Assert Type of Variable in Python

In this example, the assert statements check whether the types of the variables a and b are str and int, respectively. If any of the assertions fail, it raises an AssertionError. If both assertions pass, the program continues and prints the values of a and b.

Python3




# Initializing variables
a = "hello"
b = 42
 
# Asserting the type of a variable
assert type(a) == str
assert type(b) == int
 
# Printing the values of a and b
print("a =", a)
print("b =", b)


Output:

a = hello
b = 42

Asserting dictionary values

In this example, the assert statements check whether the values associated with the keys “apple”, “banana”, and “cherry” in the dictionary my_dict are 1, 2, and 3, respectively. If any of the assertions fail, it raises an AssertionError. If all assertions pass, the program continues and prints the contents of the dictionary.

Python3




# Initializing a dictionary
my_dict = {"apple": 1, "banana": 2, "cherry": 3}
 
# Asserting the contents of the dictionary
assert my_dict["apple"] == 1
assert my_dict["banana"] == 2
assert my_dict["cherry"] == 3
 
# Printing the dictionary
print("My dictionary contains the following key-value pairs:", my_dict)


Output:

My dictionary contains the following key-value pairs: 
{'apple': 1, 'banana': 2, 'cherry': 3}

Python assert keyword

Python Assertions in any programming language are the debugging tools that help in the smooth flow of code. Assertions are mainly assumptions that a programmer knows or always wants to be true and hence puts them in code so that failure of these doesn’t allow the code to execute further. 

Similar Reads

Assert Keyword in Python

In simpler terms, we can say that assertion is the boolean expression that checks if the statement is True or False. If the statement is true then it does nothing and continues the execution, but if the statement is False then it stops the execution of the program and throws an error....

Python assert keyword Syntax

In Python, the assert keyword helps in achieving this task. This statement takes as input a boolean condition, which when returns true doesn’t do anything and continues the normal flow of execution, but if it is computed to be false, then it raises an AssertionError along with the optional message provided....

Practical Application

...

Why Use Python Assert Statement?

...