Open In App

Python | Assertion Error

Last Updated : 16 Aug, 2021
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Assertion Error 
Assertion is a programming concept used while writing a code where the user declares a condition to be true using assert statement prior to running the module. If the condition is True, the control simply moves to the next line of code. In case if it is False the program stops running and returns AssertionError Exception. 

The function of assert statement is the same irrespective of the language in which it is implemented, it is a language-independent concept, only the syntax varies with the programming language. 

Syntax of assertion: 
assert condition, error_message(optional)

Example 1: Assertion error with error_message.  

Python3




# AssertionError with error_message.
x = 1
y = 0
assert y != 0, "Invalid Operation" # denominator can't be 0
print(x / y)


Output : 

Traceback (most recent call last):
  File "/home/bafc2f900d9791144fbf59f477cd4059.py", line 4, in 
    assert y!=0, "Invalid Operation" # denominator can't be 0
AssertionError: Invalid Operation

The default exception handler in python will print the error_message written by the programmer, or else will just handle the error without any message. 
Both of the ways are valid.

Handling AssertionError exception: 
AssertionError is inherited from Exception class, when this exception occurs and raises AssertionError there are two ways to handle, either the user handles it or the default exception handler. 
In Example 1 we have seen how the default exception handler does the work. 
Now let’s dig into handling it manually.

Example 2  

Python3




# Handling it manually
try:
    x = 1
    y = 0
    assert y != 0, "Invalid Operation"
    print(x / y)
 
# the errror_message provided by the user gets printed
except AssertionError as msg:
    print(msg)


Output : 

Invalid Operation

Practical applications. 
Example 3: Testing a program. 

Python3




# Roots of a quadratic equation
import math
def ShridharAcharya(a, b, c):
    try:
        assert a != 0, "Not a quadratic equation as coefficient of x ^ 2 can't be 0"
        D = (b * b - 4 * a*c)
        assert D>= 0, "Roots are imaginary"
        r1 = (-b + math.sqrt(D))/(2 * a)
        r2 = (-b - math.sqrt(D))/(2 * a)
        print("Roots of the quadratic equation are :", r1, "", r2)
    except AssertionError as msg:
        print(msg)
ShridharAcharya(-1, 5, -6)
ShridharAcharya(1, 1, 6)
ShridharAcharya(2, 12, 18)


Output : 

Roots of the quadratic equation are : 2.0  3.0
Roots are imaginary
Roots of the quadratic equation are : -3.0  -3.0

This is an example to show how this exception halts the execution of the program as soon as the assert condition is False. 

Other useful applications :  

  • Checking values of parameters.
  • Checking valid input/type.
  • Detecting abuse of an interface by another programmer.
  • Checking output of a function.

 



Similar Reads

Python Value Error :Math Domain Error in Python
Errors are the problems in a program due to which the program will stop the execution. One of the errors is 'ValueError: math domain error' in Python. In this article, you will learn why this error occurs and how to fix it with examples. What is 'ValueError: math domain error' in Python?In mathematics, we have certain operations that we consider un
4 min read
How to Navigating the "Error: subprocess-exited-with-error" in Python
In Python, running subprocesses is a common task especially when interfacing with the system or executing external commands and scripts. However, one might encounter the dreaded subprocess-exited-with-error error. This article will help we understand what this error means why it occurs and how to resolve it with different approaches. We will also p
4 min read
Python | Prompt for Password at Runtime and Termination with Error Message
Say our Script requires a password, but since the script is meant for interactive use, it is likely to prompt the user for a password rather than hardcode it into the script. Python’s getpass module precisely does what it is needed. It will allow the user to very easily prompt for a password without having the keyed-in password displayed on the use
3 min read
Python IMDbPY - Error Handling
In this article we will see how we can handle errors related to IMDb module of Python, error like invalid search or data base error network issues that are related to IMDbPY can be caught by checking for the imdb.IMDbErrorexceptionIn order to handle error we have to import the following from imdb import IMDbError Syntax : try : # code except IMDbEr
2 min read
How to print the Python Exception/Error Hierarchy?
Before Printing the Error Hierarchy let's understand what an Exception really is? Exceptions occur even if our code is syntactically correct, however, while executing they throw an error. They are not unconditionally fatal, errors which we get while executing are called Exceptions. There are many Built-in Exceptions in Python let's try to print the
3 min read
Create Error Bars in Plotly - Python
Plotly is a Python library that is used to design graphs, especially interactive graphs. It can plot various graphs and charts like histogram, barplot, boxplot, spreadplot, and many more. It is mainly used in data analysis as well as financial analysis. plotly is an interactive visualization library. Error Bars in Plotly For functions representing
3 min read
Error Handling in Python using Decorators
Decorators in Python is one of the most useful concepts supported by Python. It takes functions as arguments and also has a nested function. They extend the functionality of the nested function. Example: C/C++ Code # defining decorator function def decorator_example(func): print("Decorator called") # defining inner decorator function def
2 min read
Broken Pipe Error in Python
In this article, we will discuss Pipe Error in python starting from how an error is occurred in python along with the type of solution needed to be followed to rectify the error in python. So, let's go into this article to understand the concept well. With the advancement of emerging technologies in the IT sector, the use of programming language is
4 min read
How to Calculate Mean Absolute Error in Python?
Mean Absolute Error calculates the average difference between the calculated values and actual values. It is also known as scale-dependent accuracy as it calculates error in observations taken on the same scale. It is used as evaluation metrics for regression models in machine learning. It calculates errors between actual values and values predicte
2 min read
How to fix: "fatal error: Python.h: No such file or directory"
The "fatal error: Python.h: No such file or directory" error is a common issue encountered when compiling C/C++ code that interacts with Python. This error occurs when the C/C++ compiler is unable to locate the Python.h header file, which is part of the Python development package required for compiling code that interacts with Python.In this articl
5 min read
How to Fix - KeyError in Python – How to Fix Dictionary Error
Python is a versatile and powerful programming language known for its simplicity and readability. However, like any other language, it comes with its own set of errors and exceptions. One common error that Python developers often encounter is the "KeyError". In this article, we will explore what a KeyError is, why it occurs, and various methods to
5 min read
Python Django Handling Custom Error Page
To handle error reporting in Django, you can utilize Django's built-in form validation mechanisms and Django's error handling capabilities. In this article, I'll demonstrate how to implement error handling. If there are errors in the form submission, the user will be notified of the errors. Required Modules Install DjangoCreate Virtual Env Python D
4 min read
How to Fix Python Pandas Error Tokenizing Data
The Python library used to analyze data is known as Pandas. The most common way of reading data in Pandas is through the CSV file, but the limitation with the CSV file is it should be in a specific format, or else it will throw an error in tokenizing data. In this article, we will discuss the various ways to fix Python Pandas Error Tokenizing data.
4 min read
Indentation Error in Python
In this article, we will explore the Indentation Error in Python. In programming, we often encounter errors. Indentation Error is one of the most common errors in Python. It can make our code difficult to understand, and difficult to debug. Python is often called a beautiful language in the programming world because we are restricted to code in a f
3 min read
Correcting EOF error in python in Codechef
EOF stands for End Of File. Well, technically it is not an error, rather an exception. This exception is raised when one of the built-in functions, most commonly input() returns End-Of-File (EOF) without reading any data. EOF error is raised in Python in some specific scenarios: Sometimes all program tries to do is to fetch something and modify it.
3 min read
Floating point error in Python
Python, a widely used programming language, excels in numerical computing tasks, yet it is not immune to the challenges posed by floating-point arithmetic. Floating-point numbers in Python are approximations of real numbers, leading to rounding errors, loss of precision, and cancellations that can throw off calculations. We can spot these errors by
8 min read
NZEC error in Python
While coding in various competitive sites, many people must have encountered NZEC errors. NZEC (non zero exit code) as the name suggests occurs when your code is failed to return 0. When a code returns 0 it means it is successfully executed otherwise it will return some other number depending on the type of error. When the program ends and it is su
3 min read
How To Resolve The Unexpected Indent Error In Python
In Python, indentation is crucial for defining blocks of code, such as loops, conditionals, and functions. The Unexpected Indent Error occurs when there is an indentation-related issue in your code that Python cannot interpret correctly. This error typically happens when the indentation is inconsistent or there is a mix of tabs and spaces. What is
3 min read
Resolve Stopiteration Error in Python
Python is a versatile and powerful programming language, but like any other language, it has its share of errors. One common error that developers may encounter while working with iterators is the StopIteration error. This error occurs when there are no more items to be returned by an iterator. In this article, we will delve into the basics of iter
4 min read
Handle Memory Error in Python
One common issue that developers may encounter, especially when working with loops, is a memory error. In this article, we will explore what a memory error is, delve into three common reasons behind memory errors in Python for loops, and discuss approaches to solve them. What is a Memory Error?A memory error occurs when a program tries to access me
3 min read
Python Overflowerror: Math Range Error
Python is a powerful and versatile programming language, widely used for various applications. However, developers may encounter errors during the coding process. One such error is the 'OverflowError: Math Range Error.' This article will explore what this error is, discuss three common reasons for encountering it, and provide approaches to resolve
4 min read
“CAP_IMAGES: Can't Find Starting Number” Error in Python with Resolution
The error "CAP_IMAGES: Can't Find Starting Number" typically occurs in the context of the OpenCV when attempting to open a video file or capture device. This error message indicates that OpenCV encountered difficulties in reading or parsing the video stream due to the missing or incorrect starting frame number. Why “CAP_IMAGES: Can't Find Starting
5 min read
How to Fix "Error: Metadata Generation Failed" in Python
The "Error: Metadata Generation Failed" in Python usually occurs when there's an issue with generating or reading metadata related to the Python package. This error can happen for various reasons such as: Missing or corrupted metadata files: If the metadata files associated with the Python package are missing or corrupted it can lead to the metadat
4 min read
How to Fix 'Waiting in Queue' Error in Python
In Python, handling and managing queues efficiently is crucial especially when dealing with concurrent or parallel tasks. Sometimes, developers encounter a 'Waiting in Queue' error indicating that a process or thread is stuck waiting for the resource or a task to complete. This error can stem from several issues including deadlocks, insufficient re
3 min read
How to Fix MXNet Error “Module 'numpy' Has No Attribute 'bool' in Python
In Python, while working with NumPy, you may encounter the error “Module 'numpy' has no attribute 'bool'” when importing MXNet. This issue arises due to the deprecation of the numpy.bool alias in newer versions of NumPy. In this article, we will explore various solutions to fix this error and ensure compatibility between NumPy and MXNet. What is Im
3 min read
How to Fix the "No module named 'mpl_toolkits.basemap'" Error in Python
When working with the geographic data and plotting the maps in Python we might encounter the error: ModuleNotFoundError: No module named 'mpl_toolkits.basemap' This error occurs because of the mpl_toolkits.basemap module which is part of the base map toolkit is not installed in the Python environment. In this article, we will go through the steps t
3 min read
How to fix "error: Unable to find vcvarsall.bat" in Python
If you're encountering the error "error: Unable to find vcvarsall.bat" while trying to install Python packages that require compilation, such as those involving C extensions, you're not alone. This error typically occurs on Windows systems when the necessary Visual Studio Build Tools are not installed or not properly configured. Here’s a comprehens
3 min read
Handling Access Denied Error Occurs While Using Subprocess.Run in Python
In Python, the subprocess module is used to run new applications or programs through Python code by creating new processes. However, encountering an "Access Denied" error while using subprocess.run() can be problematic. This error arises due to insufficient permissions for the user or the Python script to execute the intended command. In this artic
5 min read
How to Handle 'psycopg2.errors.invaliddatetimeformat' Error in Python
The psycopg2 library is a popular PostgreSQL database adapter for Python. While working with databases, it's common to encounter various types of errors. One such error is psycopg2.errors.InvalidDatetimeFormat. This article will delve into what causes the psycopg2.errors.InvalidDatetimeFormat error and provide practical solutions with correct code
3 min read
How to Fix 'No Module Named yfinance' Error in Python
If you encounter the 'No Module Named yfinance' error, it typically means that the library is not installed or not accessible in your current Python environment. This issue can be resolved by ensuring that yfinance is properly installed and that your Python environment is configured correctly. What is Python Code Error: No Module Named ‘yfinance’?T
3 min read
Article Tags :
Practice Tags :