What is assert in python

assert¶

Raises AssertionError if the specified expression evaluates to False.

Syntax¶

assert expression, argument

expression Required. Expression to evaluate. argument Optional. Argument passed to the exception raised.

Return Value¶

Time Complexity¶

Remarks¶

Assert statements are a convenient way to insert debugging assertions into a program. The simple form, assert expression, is equivalent to

>>> if __debug__: >>> if not expression: raise AssertionError 

The extended form, assert expression1, expression2, is equivalent to

>>> if __debug__: >>> if not expression1: raise AssertionError(expression2) 

These equivalences assume that __debug__ and AssertionError refer to the built-in variables with those names. In the current implementation, the built-in variable __debug__ is True under normal circumstances, False when optimization is requested (command line option -O). The current code generator emits no code for an assert statement when optimization is requested at compile time. Note that it is unnecessary to include the source code for the expression that failed in the error message; it will be displayed as part of the stack trace.

Читайте также:  Как сгенерировать пароль java

Assignments to __debug__ are illegal. The value for the built-in variable is determined when the interpreter starts.

Example 1¶

>>> assert 2 + 2 == 4 >>> assert 2 + 2 == 3 Traceback (most recent call last): File "", line 1, in AssertionError 

Example 2¶

>>> assert 1 == False, "That can't be right." Traceback (most recent call last): File "", line 1, in AssertionError: That can't be right. 

Источник

Python — Assert Statement

In Python, the assert statement is a powerful tool that helps with debugging and handling errors during development. It allows you to make assumptions about the code and catch potential issues early on.

The assert statements can be useful when testing functions or methods, as it allows you to ensure that the function is behaving as expected. Additionally, assert statements can be used to enforce certain conditions on the inputs or outputs of a function, such as ensuring that a parameter is within a certain range or that a return value meets certain criteria.

Syntax

assert condition [, Error Message] 

The assert statement works by evaluating a boolean condition and raising an AssertionError if the expression is false. If the specified condition evaluates to True then it continues to execute next statements, otherwise it raises the AssertionError exception with the specified error message.

The following example demonstrates a simple assert statement.

def division(x,y): assert y!=0, "y cannot be zero" print(x/y) division(10,2) #5 division(10,0) #AssertionError: y cannot be zero 

In the above example, the division() function contains the assert statement to check whether the y parameter is zero or not. If the assert condition y!=0 evalutes to be True, then it will continue to execute the next statement without any error. If it is true then it will raise an AssertionError with the error message y cannot be zero .

The AssertionError is a built-in exception that can be handled using the try-except block, as shown below:

def division(x,y): assert y!=0, "y cannot be zero" print(x/y) #call division() function in try block try: division(10,0) except AssertionError as msg: print(msg) 

Above, calling division(10,0) will raise an AssertionError , which will be handled by the except block. The error message in the assert statement will be passed as an argument to the exception argument msg , using as keyword.

In this way, the assert statements should be used in conjunction with other error handling techniques, such as try-except blocks and logging, to ensure that your code is robust and reliable.

Thus, the assert statement is a valuable tool for any Python developer looking to improve their debugging and error handling skills.

  • Compare strings in Python
  • Convert file data to list
  • Convert User Input to a Number
  • Convert String to Datetime in Python
  • How to call external commands in Python?
  • How to count the occurrences of a list item?
  • How to flatten list in Python?
  • How to merge dictionaries in Python?
  • How to pass value by reference in Python?
  • Remove duplicate items from list in Python
  • More Python articles

Источник

An Introduction to Assert in Python [With Examples]

An Introduction to Assert in Python With Examples

An assertion is nothing but a sanity check that can be turned off or turned on when the program testing is completed. The simplest method to think about an assertion is as an improvement on the “if statement”. During the testing of an expression, when the result of the test is false, then an exception can be raised. Often, assertions are placed at the beginning of the function for checking the valid input, and the valid output after the function call.

What is Assertion?

In the programming world, assertion is a fact of state. It describes the anticipated state at the end of the code execution.

Assertion is a Boolean-valued function, which returns the assumption of output as true or false. The current world of programming languages includes assertions that are used to roughly verify or during the runtime.

Programmers use assertion as a tool to debug the program. It brings down the location where the logical inconsistency is found and makes the assertion evaluations false during the execution time. As soon as the assertion evaluates to false, the programs design to stop further execution of lines and throw the user-friendly/debug friendly errors.

Launch Your Career into the Clouds!

Not surprisingly, python also has its own assert statement that can be used by developers. Let us see the assertion flow now for quick understanding.

High level illustration of an assertion in a program.

assertioninprogram_1

Thus, the assert in Python or any other programming language does the following.

  • If the programming line or execution of code passes, assertions return true.
  • If the programming line or execution of code fails, assertions return false.

Essence of Assert in Python:

Why Assert in Python?

Like few other programming languages, Python also has its built-in assert

statement, which is used to continuously execute the condition if assert evaluates to True, else it will return the AssertionError i.e., Exception.

Where assert in Python is used?

Verifying the expected output of the functions.

Developer while testing the code or a program.

Validating the values in the argument to know whether it is valid.

Syntax – Assert in Python:

In Python, assert statements are being used in two ways as mentioned below.

Two-way declarations of python are detailed below.

assert ,

This type of assert declaration has an expression to be evaluated, and an optional error message.

Here, if the expression evaluation failed or not satisfied, then the assert statement gives AssertionError along with the error message, which is defined.

assert

This type of assert declaration has expression only to be evaluated. The optional user defined error message will not be available.

Here, if the expression evaluation failed or not satisfied, then the assert statement gives AssertionError but not the error message.

Prerequisites for starting the hands-on.

Installation of Visual Studio Code and the Extension for Python.

1. Install VS Code if not already done.

InstallVSCode

2. Next, Python extension for VS Code for Visual Studio Code (VS Code).

The Python extension can be found in Extension Market Place in VS Code.

PythonextensionforVSCod

3. Installation of Python Interpreter.

For further clarification, please refer to the examples below.

Kickstart Your UI/UX Career Right Here!

Scenario 1:

We have written a program to find total marks. The condition is that subject marks can be aggregated.

So, the program should execute only less than or equal to 5 subject marks.

If more than 5 subject marks are entered, then the program should abort.

Step 1: Defining sum function in Python.

Step 2: Initialize array variables with 6 values.

Step 3: Since the array variable is more than 6 values, assertionError will be thrown.

Step 4: In example1 assertionError will be thrown without error message.

Step 5: In example2 assertionError will be thrown with error message.

Example 1: Using Assert in Python without Error Message

aggregateMarks

Output:

Program returned AssertionError and Aborted.

Explanation

In example 1, we have initialized the mark array variable with

6 marks, whereas the expected array input is up to 5 marks only.

Hence, the Python interpreter generated an exception at run time. Here, we see only the AssertionError as we have specified the optional error message for assertion.

Example 2: Using Assert in Python with Optional Error Message.

File Name: aggregateMarks.py

aggregateMarks.py

Output:

Program returned AssertionError along with the error message that we specified.

Explanation:

In example 2, we have initialized the mark array variable with 6 marks, whereas the expected array input is up to 5 marks only.

Hence, the Python interpreter generated an exception at run time. Here,

we can see error messages along with AssertionError.

Become a Data Scientist With Real-World Experience

Scenario 2:

Let us try a simple additional and subtraction calculator in Python. Along with using Assert in Python.

Step 1: Defining Addition and Subtraction function in Python.

Step 2: Print the title ‘Choose calc operation to perform.

Step 3: Ask for a choice that the user wants to perform calculation.

Step 4: Ask the number 1 and number 2 that the user wants to perform calculation for.

Step 6: If user entered invalid choice, then throw AssertionError with optional

Step 7: Program will be aborted.

Example 1:

Calculator.py

Output:

Program returned AssertionError along with the error message that we specified.

Calculator.py_output

Explanation:

Since user entered second number as greater than first number, program

aborted and threw AssertionError with the error message that is defined in the program.

Hands-on Challenge

Get Ready

You will be completing this challenge on your own with above specified examples. Here, the challenge is nothing but like scenario 2. In the above, we had to add and sub Python functions. For your challenge, you can use or define division or multiplication function, throw the error using statement assert in python.

Looking forward to making a move to the programming field? Take up the Python Training Course and begin your career as a professional Python programmer

Conclusion

An assertion is a sanity test like behavior that is used to check whether the evaluation returns the expected outcome, which is basically true or false. When an expression is evaluated and the result is false, then it throws an exception, else move forward or execute the further programming.

Assertion helps to write a clean and maintainable code. In addition to that, it also behaves like a debugging tool to throw error if the result of an outcome is false. However, it is not a try-catch in the programming.

You can learn more about assert in python by joining the Python Training Course from Simplilearn that will teach you the fundamentals of Python, data operations, conditional statements, shell scripting, and Django. This certification course consisting of 38 hours of Blended Learning and 8 hours of online self-paced learning will provide you with practical programming experience and train you for a rewarding career as a professional Python programmer.

Have any questions for us? Leave them in the comments section of this article, and our experts will get back to you on them, as soon as possible!

About the Author

Simplilearn

Simplilearn is one of the world’s leading providers of online training for Digital Marketing, Cloud Computing, Project Management, Data Science, IT, Software Development, and many other emerging technologies.

Источник

Оцените статью