×

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

Python Dictionary copy() method

Python Dictionary copy() method The dictionary.copy () method in Python returns a copy of the specified dictionary. Syntax dictionary.copy () Parameter NA Return None Example 1 # Python program explaining # the dictionary.copy() method # initialising the dictionary ...

1 minute read.

Artificial intelligence mini projects with source code in Python

Project Name: Movie recommendation system A recommendation provides customers with relevant information related to their searches. Before the recommendation system, the most common method of purchasing was to rely on the...

4 minutes read.

Python id() function

Python id() function The id() function in Python returns an id for the specified object where all the objects in has its own unique id. Syntax id(object) Parameter object: This parameter represents any object, String, Number, List,...

1 minute read.

Python Rest API

In this tutorial, we will understand the meaning of API and REST API. We will understand the working of REST API. We will then realize the boundaries of architecture defined...

4 minutes read.

Nested Tuple in Python

If you are a Python learner, this page contains all the information that helps you know about nested tuple and how to access it in python. What is a Tuple? Multiple items...

4 minutes read.

An Introduction to Subprocess in Python with Examples

Subprocess in Python By starting new processes, the Python function subprocess is utilized to run extra programs and applications. It makes it possible to run brand-new apps straight from a Programming...

6 minutes read.

Python Random shuffle( ) method

The shuffle() is used to change the positions of the elements in the mutable sequences. The shuffle( ) function will change the positions of the elements in the sequence of...

3 minutes read.

Python whois

What is whois? Whois is a protocol used to identify the owner of the registered domain name. It is a querying database that is used to record the registered users. WHOIS is...

4 minutes read.

Python lambda() Function

In this tutorial, we will learn about a new concept known as the Lambda function. It is a relatively new concept while learning Python. Python lambda functions are anonymous functions. It...

3 minutes read.

Writing to a CSV file in Python

Python is an Object-Oriented high-level language. Python has an English-like syntax, which is very easy to read and write codes. Python is an interpreted language which means that it uses...

6 minutes read.

Python Program for Tower of Hanoi

In this tutorial, we will examine and learn about the Python coding used to create the video game Tower of Hanoi. Before seeing the game's step-by-step implementation in Python, we...

3 minutes read.

How To Compare Two Strings In Python

In this article, we will discuss how to compare two strings in Python. So, before that, let’s have a quick revision on “What are strings?” Strings are a sequence of characters that...

5 minutes read.

Python Program to find the length of a string

Python program to find the length of a string A string in Python is a set of Unicode characters. It can't be changed once it's been declared. The number of characters...

2 minutes read.

Python String rstrip() method

Python String rstrip() method The string.rstrip() method in Python returns a copy of the string with trailing characters removed. Syntax string.rstrip([chars]) Parameter chars:  This argument represents a string specifying the set of characters to be...

1 minute read.

List Iteration in Python

In this tutorial, we will learn how to iterate list in Python. List in Python A list is an ordered group of values which includes several kinds of values.A list is a mutable...

3 minutes read.

SKLearn Model Selection

The model selections of SK learn has many functions with which we can work on.It has functions to cross-validate the model and, it also provides validation and learning curves.It is...

3 minutes read.

Colors in Python

Adding colour to your visualisations will help them come to life. Even if you know the colours you want to use, picking good ones and putting them into practise might...

4 minutes read.

Simple GUI calculator using PyQt5 in Python

GUI: The user is provided with information using manipulable visual widgets that don't require command-line input. These interface components respond to the user's interactions per the pre-programmed script, assisting each user's...

4 minutes read.

Sentiment Analysis using NLTK

Introduction Data is being produced at an astounding rate and volume in the field of the internet and other digital services nowadays. Researchers, engineers, and data analysts often work with tabular...

7 minutes read.

Expressions in Python

What is Expression in Python? The expression contains more than one operator as well as the operands with it. Expression helps us to produce some other values. In the Python programming...

12 minutes read.