Topics

Assert Statement

Welcome to another tutorial, here you will learn about Assert Statement in Python.

Coding in virtually all programming languages, assertions are typically used to verify if a specified condition is true or not now, take for example, if we have a function to add two numbers, before applying the +operator to add the two numbers provided by a user. 

In addition, the Assert statement contains a Boolean expression that checks for the trueness of a condition and adequately returns true if found valid otherwise, returns false.

If an Assertion is used in a program, therefore, for positive assertion the program will continue its execution normally, but for the negative assertion, the program will stop its execution and an error will be thrown.

 

Python assert statement

Python provides a built-in assert statement, that can be used to implement assertions in any program if required. This assert statement takes a condition or an expression as an argument and expects it to be true for the program to continue its execution. However, if the condition/expression is false, the statement will throw an AssertionError, which results in the interruption of the normal execution of the program.

In Python Assertion is the pythonic way of applying conditions for validations where if...else conditions are commonly used.

We will take an example to understand when and where to use an assert statement. Now, if you have a program to take Password as input from a user, in which the input should be checked if it is a strong password and if found strong it should be stored, else the user should be asked to re-enter the password. 

For the case above, we can use an assert statement to apply various conditions to the input password value to check if it's a strong password. Thus, if the conditions return true then the program will continue to store the password else the assert statement will throw an AssertionError. How good is this? It is great.

 

Syntax of the assert statement:

The are two ways to declare an Assert statement.

assert <condition> 

# with condition and error message 

assert <condition>, <error message>

From above, the first type of syntax, the assert statement will only check the condition and when the condition is false, an error assertion will be raised. For the second case, the assert statement will also print a message with an assertion error when the condition is false.

 

Example for Assert Statement

Below is an example in which we will be defining a function to find the percentage of marks scored, where a list of marks scored out of 100 will be provided. The assert statement will be used to make sure no marks entered in the list are negative marks.

# function to calculate percentage, given a list of marks out of 100
def percentage(marks):
  for m in marks:
    # marks should always be a positive value
    assert m > 0,
  return (sum(marks)/len(marks))
  
print(percentage([90,93,99,95,-94]))

Output:

It will show error

 

As shown in the above example, one negative value was provided and the program failed with an AssertionError, otherwise, it would have executed successfully and returned the result.

So, we will update the above program to include a message in the assert statement to be shown along with the assertion error. Check below:

# function to calculate percentage, given a list of marks out of 100
def percentage(marks):
  for m in marks:
    # marks should always be a positive value
    assert m > 0, "Only positive values allowed"
  return (sum(marks)/len(marks))
  
print(percentage([90,93,99,95,-94]))

 

Important points to note

  • Assert is not similar to try...except, however, the try...except is used for dealing with a recoverable error that can be followed by a corrective measure, but the assert statement is simply used for the errors which either can't be recovered or any corrective measure is not required for them.
  • Also, the Assert is a statement, not a function, as such, don’t ever use it with parentheses. Now, if we attempt to execute the following assert(condition, message), the assert will execute with a tuple as the first argument; because it will take (condition, message) as a tuple input.

Check out the example below to see the behavior of the assert statement as an input.

if not condition:
    raise AssertionError()

However, it is not entirely like this but behaves like this.

In addition, suppose in your program there are many assert statements and you want to disable all the assert statements, run the python script in optimized mode by using the -o flag.

python -o yourscript.py

It is because, in optimized mode __debug__ is false and as per the official documentation of python, the assert statement is equivalent to:

if __debug__:
   if not expression: raise AssertionError

Thus, if the __debug__ is false, then the assert statements are disabled.