- Trending Categories
- Data Structure
- Operating System
- C Programming
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
What is the use of "assert" statement in Python?
The assert statement has the following syntax.
assert <some_test>, <message>
The line above is read as: If <some_test> evaluates to False, an exception is raised and <message> will be output.
If we want to test some code block or an expression we put it after an assert keyword. If the test passes or the expression evaluates to true nothing happens. But if the test fails or the expression evaluates to false, an AssertionError is raised and the message is printed out or evaluated.
Assert statement is used for catching/testing user-defined constraints. It is used for debugging code and is inserted at the start of a script.
It is not used for catching code errors like x / 0, because Python catches such errors itself.
Given code can be tested using assert statement as follows:
x,y = 4,7 assert x > y, "x has to be smaller than y"
Traceback (most recent call last): File "C:/Users/TutorialsPoint1/~assert2.py", line 2, in <module> assert x > y, "x has to be smaller than y" AssertionError: x has to be smaller than y
- What is the use of "from...import" Statement in Python?
- What is the use of "from...import *" Statement in Python?
- What is the use of "is" keyword in C#?
- What is the use of "placement new" in C++?
- What is "is not" operator in Python?
- What is "not in" operator in Python?
- What is the importance of "Java.lang.Class" in Java?
- What is the difference between "var" and "val" in Kotlin?
- What is the difference between "const" and "val" in Kotlin?
- What is called "Angle of Banking"?
- What is the difference between "std::endl" and "\n" in C++?
- What is python .. ("dot dot") notation syntax?
- What is difference in Python operators != and "is not"?