The “assert” is a keyword in Python that ensures the correct functioning of code while debugging the program. The “assert” keyword acts as the boolean check to determine the health of the code, if the program executes properly, it returns true and displays output on the kernel. However, if the statement is false, it raises the “AssertionError” and terminates the program. 

This article will elaborate on the usage of “assert” in Python. The article covers the following topics:

  • What is the Use of “assert” in Python?
  • Check the Values Behaviour Between Elements
  • Printing the Error Message in Case Error Arises
  • Defining a Function To Use “assert” Inside It
  • Using “assert” to Check the DataType of the Variables
  • Using “assert” in Dictionaries to Check the Index Location of the “key-value” pair

What is the Use of “assert” in Python?

The assert keyword takes a statement, or the expression as input, however, it is utilized to check for data types, values, and the program functionality. The following syntax depicts to use of the “assert” keyword in Python:

assert condition, message (Optional)

Example 1: Check the Values Behaviour Between Elements

To check the behavior of the values between two or more elements, utilize the “assert” keyword. The “assert” keyword will be a boolean check for that particular condition. For demonstration, follow the below example code: 

# considering list of integers number
list1=[1,2,3]
list2=[4,5,6]

print("list 1:", list1)
print("list 2:", list2)

#assert checks for the length of two lists
assert len(list1)==len(list2)
print("\nThe sum of integers of list:", sum(list1 + list2))

The above code will check whether the length of two lists is equal or not using the “len()” function and comparison operator (==). The “assert” will check for the length of lists. If the length matches, it passes the statement to compute it, otherwise returns the “AssertionError”.

Output

Printing the Error Message in Case Error Arises

In most scenarios, if the program doesn’t function properly, by default the execution error arises by the interpreter itself and the program terminates the interpreter console upon displaying the error. In tackling such scenarios, Python gives flexible access to users to use the “assert” to print the error message upon unsuccessful execution. 

For a demonstration of the use of “assert” in Python, follow the below example code: 

# considering list of integers number
list1=[1,2,3]
list2=[4,5,6]

print("list 1:", list1)
print("list 2:", list2)


#assert checks for the length of two lists
assert len(list1)==len(list2), "List of unequal length so can't compute"
print("\nThe sum of integers of list:", sum(list1 + list2))

The above program will check for the length of two integers containing lists using the comparison operator “(==)”. If the length of two lists is equal, the program computes the lists and returns the results. If the length of lists is unequal it returns the particular stated error as 

AssertionError: List of unequal length so can't compute

Output

The length of the list does not match so it raises the “AssertionError

Example 2: Defining a Function To Use “assert” Inside It

Python language gives flexible access to use the “assert” inside the function. To do so, use the “assert” keyword inside the code body. For implementation follow the below example code: 

# defined a user-defined function using "def" keyword
def perimeter_square(length):
	# Assertion condition to determine that the provided length must be of +ve value
	assert length > 0, "\n Length of square must be positive"
#computing perimeter of square
	area = 4*length
	# function passing some "return" value
	return area

# invoke a function with argument value
area1 = perimeter_square(4)
print("Perimeter of Square with +ve length value: \n", area1)

# invoke a function with argument value
area2 = perimeter_square(-4)
print("Perimeter of Square with -ve length value", area2)

In the above example code, the perimeter of the square is computed by defining a user-defined function using the “def” keyword. The value will return the perimeter of the square if the length is a positive integer value. However, if the length is of negative integer value it will raise an “AssertionError” with the provided message statement. 

Output

The perimeter of the square returns the output for the length having a positive value of an integer. However, for the negative value of the length, it raises “AssertionError”:

Example 3: Using “assert” to Check the DataType of the Variables

To check the variables of which datatype utilizes the type() function, however, to determine that the particular variable belongs to a particular datatype, use the “assert” keyword aggregation with the “comparison operator”.  For demonstration, follow the below example code: 

# consider a variables
string = "linuxuser"
string1 = 42

# using "assert" to check the type of the variable
assert type(string) == str
assert type(string) == int

#print variables
print("String  =", string)
print("Integer =", string1)

If any of the assertion doesn’t match it raises the “AssertionError”. To execute the program successfully, both variables should be of the same data type. 

Output

In the example code, one variable is of string and the other is an integer, so the program failed by raising the “AssertionError”: 

Example 4: Using “assert” in Dictionaries to Check the Index Location of the “key-value” Pair

To determine the index location of the “key-value” pair in the dictionary utilize the “assert” keyword in Python. In the below example program, the “assert” keyword is used to check the “keys” index location with the help of the “comparison operator” (==). To check the use of “assert” follow the below example code: 

# construct a dictionary
data = {1: "city", 2: "location", 3: "postal code"}

# check for dictionary key-value pair 
assert data[1] == "city"
assert data[2] == "location"
assert data[3] == "code"

# Printing the Dict data 
print("Dictionary Data:", data)

The above example code checks the assertion of the dictionary key-value pairs. Using the comparison operator (==), it searched and matched the data with the provided dictionary. If the “key” doesn’t match with the provided “value”, the “assert” will raise the “AssertionError” and terminate the program. 

Output

The dictionary “key” doesn’t match with the “value”, it returns the “AssertionError”: 

Another prevalent use of the “assert” is to implement it on the “for…in” structure to check for the condition and print the user-defined message. For demonstration, follow the below example code: 

# consider a temperature record
temp = [ 30, 27, 26, 29, 32, 35]

# using assert to check for temperature less than or equal to average record temp
for i in temp:
	assert i <= 30, "\n increase in temperature recorded"
	print (str(i) + " normal temperature" )

For the temperature greater than 30, the “assert” condition becomes “True” and raises an “AssertionError”, however, for the values less than or equal to 30, the “assert” condition is “False”, so returns the output on the console for all “True” values.

Output

For temperature, greater than 30 the “assert” raises the “AssertionError”: 

That’s all about how to use the “assert” in Python. 

Conclusion

The use of “assert” in Python is straightforward, you just need to utilize the “assert” keyword in the program to check the working of the particular program. The “assert” acts as a boolean, if the condition of the program is true it displays output on the kernel console. However, if the program condition is false, the “assert” keyword raises the “AssertionError”. This article has demonstrated the use of “assert” in Python.