Open In App
Related Articles

Python assert keyword

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Report issue
Report

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. 

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.

Flowchart of Python Assert Statement

assert in Python

Flowchart of Python Assert Statement

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}

Practical Application

This has a much greater utility in the Testing and Quality Assurance roles in any development domain. Different types of assertions are used depending on the application. Below is a simpler demonstration of a program that only allows only the batch with all hot food to be dispatched, else rejects the whole batch.

Python3

# Python 3 code to demonstrate
# working of assert
# Application
 
# initializing list of foods temperatures
batch = [ 40, 26, 39, 30, 25, 21]
 
# initializing cut temperature
cut = 26
 
# using assert to check for temperature greater than cut
for i in batch:
    assert i >= 26, "Batch is Rejected"
    print (str(i) + " is O.K" )

                    

Output:

40 is O.K
26 is O.K
39 is O.K
30 is O.K

Runtime Exception:

AssertionError: Batch is Rejected

Why Use Python Assert Statement?

In Python, the assert statement is a potent debugging tool that can assist in identifying mistakes and ensuring that your code is operating as intended. Here are several justifications for using assert:

  1. Debugging: Assumptions made by your code can be verified with the assert statement. You may rapidly find mistakes and debug your program by placing assert statements throughout your code.
  2. Documentation: The use of assert statements in your code might act as documentation. Assert statements make it simpler for others to understand and work with your code since they explicitly describe the assumptions that your code is making.
  3. Testing: In order to ensure that certain requirements are met, assert statements are frequently used in unit testing. You can make sure that your code is working properly and that any changes you make don’t damage current functionality by incorporating assert statements in your tests.
  4. Security: You can use assert to check that program inputs comply with requirements and validate them. By doing so, security flaws like buffer overflows and SQL injection attacks may be avoided.


Last Updated : 05 May, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads