×

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

Dictionary to JSON Python

In python JSON (JavascriptObject Notation). In the programming language, the text file is made using the script file.We can use many built-in packages which arenamedJSON.Before using the packages, we have...

3 minutes read.

How to Convert int to str in Python

How to Convert int to str in Python In the last article, we studied how we convert a variable with string datatype to integer datatype and discussed different data types available...

4 minutes read.

Python type() Function

Python type() Function The type() function in Python returns the type of an object. The return value is a type object and generally the same object as returned by object.__class__. Syntax class type(object)      ...

1 minute read.

Not supported between instances of str and int in python

In this article, you are going to learn why the type error occurs between instances of string and integer datatypes. Also, you will know what kind of error is the...

6 minutes read.

Accuracy_score Function in Sklearn

A crucial stage in data science is measuring our model's performance using the appropriate metric. In this article, we will examine two methods for calculating the accuracy of your predictions:...

13 minutes read.

Python Tutorial

Python tutorial is a widely used programming language which helps beginners and professionals to understand the basics of Python programming easily. Python is a high-level, easy, interpreted, general-purpose, and dynamic programming...

19 minutes read.

Python Ways to find nth occurrence of substring in a string

Introduction In Python, a string is a collection of characters that can be employed to conduct additional operations. In Python, a substring is a group of characters that are a part...

4 minutes read.

How to Take Input in Python

How To Take Input In Python Python has various in-built functions that help in code redundancy. Let's discuss the usage of some functions- ascii() – it returns a readable representation of objects.format()...

4 minutes read.

XXhash Python

Python: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It is said...

6 minutes read.

Python map() function

Python map() function The map() function in Python returns an iterator that applies a function to every item of iterable, yielding the results. Syntax map(function, iterable, ...) Parameter function: It is a required parameter that represents the function to...

1 minute read.

*Args and **Kwargs in Python

Let’s know about ** (dual star / asterisk) and * (star / asterisk) are operators in Python. These stars are used in Python for parameters. Args and kwargs are special...

3 minutes read.

Python PyMOTW

The cmd module comprises one class of the general public, Cmd, meant for command processors such interactive shells and other command interpreters as a foundation class. It utilises readline as...

3 minutes read.

Convert int to Float in Python using Pandas

Introduction We have already learnt about how to convert float variables to int. Now let us know how to convert int variables to float So let us create another Dataset on which...

2 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.

Python Permutations and Combinations

In mathematics, we all studied what is meant by permutations and combinations. “Permutations” define the way of arranging the elements in sequential order. “Combinations” mean the way of selecting the...

7 minutes read.

Converting Set to List in Python

Converting ‘set’ datatype to ‘list’ datatype is called typecasting. Typecasting in programming is a method to convert one datatype into another datatype. It may happen implicitly by the defined language, called...

3 minutes read.

How to check the version of the Python Interpreter?

As we all know what an interpreter is, and how important it is. We should also be aware of the fact that it is important to have knowledge of the...

2 minutes read.

Python program to find the area of the triangle

Python program to find the area of the triangle This article will discuss how to find the area of a triangle in Python with all three given sides. The area of...

2 minutes read.

How to Install Python In Windows

How To Install Python In Windows? Python is a language that every aspirant developer looks forward to. One thing we must keep in our mind is how to begin our hands-on...

3 minutes read.

Python's Qstandarditemmodel

Python More interactive and user-friendly than any other programming language is Python. Many libraries are used by the python programming language to speed up procedures. Python can be used to develop...

3 minutes read.