×

Assertion Errors and Attribute Errors in Python

Assertion Error in Python

In Python, the assert condition is used to continue the execution if the given statement displays true. If the assert statement displays false, it raises Assertion Error exception with user defined error message. If the statement is true, the process will move to the next statement of code. If it fails, the program stops the execution and displays Assertion Error Exception.

Assertion Error is a language independent concept. Its syntax was different from programming language and when we are implementing the Assert condition, it ignores the same language.

Assertion syntax:

Assert condition, error message (optional)

Example

// python program to illustrate Assertion Error with error message
# Assertion Error with error message.
a =1
b =0
assertb !=0, "Invalid Operation"// denominator can't be 0
print (a /b)

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

As we known that when a denominator divides with 0, an error will be displayed. The exception handler in Python displays the user defined error message as written in code or directly it will display an error message.

Handling Assertion Error exception:

There are basically two ways to handle Assertion Errors:

  1. User handling
  2. Default exception handling

Let’s see an example for quadratic equation

// python program for quadratic equation
importmath
defquad (a, b, c):
    try:
        asserta !=0, "Not a quadratic equation as coefficient of x ^ 2 can't be 0"
        D =(b *b -4*a*c)
        assertD>=0, "Roots are imaginary"
        r1 =(-b +math.sqrt(D))/(2*a)
        r2 =(-b -math.sqrt(D))/(2*a)
        print("Roots of quad are :", r1, "", r2)
    exceptAssertionError as msg:
        print(msg)
quad (-1, 5, -6)
quad (1, 1, 6)
quad (2, 12, 18)

Output

 Roots of quad are: 2.0 3.0
Roots are imaginary
Roots of quad are: -3.0 -3.0

Attribute Errors in Python

In programming languages, when we execute programs, we face errors or exceptions in code. So, that program will not execute, or the output of the program will not be displayed. To rectify the errors, we debug the code.

Attribute Errors

Attribute Error is one of the errors which occur mostly in Python. Attribute Error can be defined as an error that is occurred when an assigned assignment or reference fails.

For example: if we take a variable y and assign a value of 5 and again if we assign another value to same variable, it is not possible.

Because, we have taken an integer type variable, it does not support the repeated values to the same variable, again and again. So, this type of problem is known as “Attribute Error”. To support the repeated value to a same variable we use list type. Then we don’t face the problem of getting “Attribute Error”.

Examples for getting an Attribute Error

Example 1

// python program to illustrate Attribute Error
J = 5
J. append (2) // raises an Attribute Error

Output:

Traceback (most recent call last):
  File "/home/46576cfdd7cb1db75480a8653e2115cc.py", line 5, in 
    X.append (2)
AttributeError: 'int' object has no attribute 'append'

Example 2

//python program to illustrate Attribute Error
// An Attribute Error raises when method as fst for strings
String = “javatpoint contains”. fst (“good content”)
Print (String)

Output:

Traceback (most recent call last):
  File "/home/2078367df38257e2ec3aead22841c153.py", line 3, in 
    string = "javatpoint contains".fst("good content")
AttributeError: 'str' object has no attribute 'fst'

Example 3

Attribute Error also occurs when user perform an incorrect Attribute reference for a user defined class.

// python program to illustrate Attribute Error.
classDemo ():
     
    def__init__(self):
        self.a ='javatpoint'
         
// Driver's code
obj =Demo()
 
print(obj.a)
 
// occurs an Attribute Error because we have not intialised b


Print(obj.b)

Output:

javatpoint
Error:
Traceback (most recent call last):
  File "/home/373989a62f52a8b91cb2d3300f411083.py", line 17, in 
Print(obj.b)
AttributeError: 'Demo' object has no attribute 'b'

Solution for Attribute Error

C programming does not provide direct support for error handling but in Python and Java programming exceptions and errors are handled by exception handling with the help of try and except in Python whereas in Java we use try and catch keywords.

Example

From above class example, we have to use exception handling for rectify or to cover come from Attribute Error.

// python program to illustrate Attribute Error
classDemo ():
     
    def__init__(self):
        self. a ='javatpoint'
 
obj =Demo ()
 
// Try and except keywords forException handling
try:
    print(obj.a)
     
    // Raises an AttributeError
    Print(obj.b)
     
// Prints the below statement
// whenever an AttributeError israised


exceptAttributeError:
    print("Attribute Error raised")

Output:

javatpoint
Attribute Error raised

Related Topics

How to Concat two Dataframes in Python

Using Pandas dataframe, we can concat two dataframes or series in Python. So let's take a brief introduction to what is Pandas in Python. Pandas is a library typically used for...

7 minutes read.

Applications of Python

Top 10 Applications of Python in 2020- 2021 Python language is famous for its general-purpose nature, which enables developers to use it in every field of development. Python can be found...

6 minutes read.

Is Python Object Oriented Programming language

In this tutorial, we will see whether python also belongs to an object-oriented programming language like several others. We will also see the advantages of using OOPs. Further, we will...

4 minutes read.

Python Set intersection() method

Python Set intersection() method The set.intersection() method in Python returns a new set with elements that are similar between two or more sets. Syntax set.intersection(set1, set2 ... etc) Parameter set1- This parameter represents the set to search for...

2 minutes read.

Python Hash Table

An Introduction to Hashing A technique which used to identify a particular object uniquely from a set of similar objects is known as Hashing. Some real-life examples of hashing implementations include: A...

9 minutes read.

Python String capitalize() method

Python String capitalize() method The string.capitalize() method in Python returns a copy of the string with only its first character capitalized. Syntax string.capitalize() Parameter NA Return This function returns a string where the first character is upper...

1 minute read.

Image to Text in python

Processing out information from an image is a very big task in all the fields of work such as in development and business sector. The process of converting an electronical...

3 minutes read.

Data Structures and Algorithms using Python | Part 2

Files: A file is a location or information stored in computer storage devices. File handling is essential when the information or the data is to be held permanently. When we try to...

20 minutes read.

Falcon Python

Introduction of Python Python is the fastest and the smartest programming language and it is an object oriented language. Python has libraries that can be importedeasily and perform many operations; to...

3 minutes read.

How to write a program in python?

How to write a program in python? In python, writing programs is not a big deal. What we need to work on is our logic and some basic rules of this...

4 minutes read.

How to Install Matplotlib in Python?

How to Install Matplotlib in Python The speed at which the enormous amount of data is generating has become a huge aid in understanding what's going on currently in the market....

4 minutes read.

Python Dictionary items() method

Python Dictionary items() method The dictionary.items() method in Python returns a view object that displays a list of dictionary's (key, value) tuple pairs. Syntax dictionary.items() Parameter NA Return This method returns a view object, displaying the list...

1 minute read.

Linear Regression using Sklearn with Example

This article will examine Python's global, local and non-local variables and show you how to use them to write code without problems. Let's quickly review what a variable in Python is...

8 minutes read.

Python enumerate() function

Python enumerate() function The enumerate() function in Python takes a collection (e.g. a tuple) and returns it as an enumerate object. Syntax: enumerate(iterable, start=0) Parameter Iterable:  This parameter represents an iterable object start:    This parameter represents a number defining...

1 minute read.

Python Logistic Regression with Sklearn & Scikit

In this article, we'll walk through a tutorial for utilising the Python Sklearn (formerly known as Scikit Learn) package to implement logistic regression. To assist you in remembering the concept,...

18 minutes read.

How to Convert Int to String in Python?

Every value we use or store in a variable in Python will have a specific data type. It describes the value's nature; based on that, Python will automatically assign a...

4 minutes read.

Python ord() Function

Python ord() Function The ord() function in Python returns the number representing the Unicode code of a specified character. Syntax ord(c) Parameter c: This parameter represents a string or any character. Return This function returns the number...

1 minute read.

Write Text files in Python

Let's discuss writing the text file in detail. Generally, writing text also follows the same procedure as like reading text. It varies only in some specific places. Steps followed for writing...

4 minutes read.

SKLearn Linear Module

The SK learn linear module is one such module that helps to study the relationship between the independent and dependent variables.The linear module can be implemented by using the best...

3 minutes read.

Unicode to String in Python

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.