×

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 run a Python file in CMD

Introduction Today, let us learn about how to run a Python file using cmd. Cmd is nothing but command prompt. So first let us know how to run a Python code...

4 minutes read.

Django vs NodeJS

Django and NodeJS are open-source frameworks used to develop web applications. Both Django and NodeJS are cross-platform and robust technology used for developing versatile web applications and mobile applications. Django Django is...

2 minutes read.

How to Substring a String in Python

String Unicode characters collection is referred to as a String. It consists of a succession of characters, including alphanumeric and special characters. Substring: Core Concept A substring is a piece of a string....

5 minutes read.

How to check version of Python

How to check version of python The versions of Python come with different kinds of features and functionalities. It is not a herculean task to keep track of the updates these...

3 minutes read.

Python CGI Programming

The Concept of CGI CGI is an abbreviation for Common Gateway Interface. It is not a type of language but a set of rules (specification) that establishes a dynamic interaction between...

9 minutes read.

Reading a File Line by Line in Python

Introduction In this tutorial, we will learn about reading files in python line by line. Before reading the files, let us know a little information about the files first. Files A file is...

6 minutes read.

Python open() function

Python open() function The open() function in Python opens a file and returns a corresponding file object. If the file cannot be opened, an OSError is raised. Syntax open(file, mode='r', buffering=1, encoding=None, errors=None, newline=None, closefd=True, opener=None) Parameter file It represents the path and name of the file mode...

2 minutes read.

Python all() Function

Python all() Function The all() function in Python returns a Boolean value ‘True’ if all the items in iterable are true or if the iterable object is empty, else it returns False. Syntax all(iterable) Parameter Iterable: An iterable object...

1 minute read.

GET and POST requests using Python

‘GET’ and ‘POST’ are two request methods of Hypertext Transfer Protocol (HTTP). What is HTTP? HTTP stands for Hypertext Transfer Protocol. It is a collection of protocols which makes communication between client...

4 minutes read.

Math Module in Python

In this article, you are going to learn everything in detail about the “ math “ module in Python. We can normally work with general operations using python without importing or...

16 minutes read.

Python delattr() function

Python delattr() function The delattr() function in Python is used to delete the named attribute from the object, with the prior permission of the object. Syntax delattr(object, name) Parameter object : This parameter represents the object from which...

1 minute read.

Artificial intelligence mini projects ideas in python

Artificial intelligence "The human race started from the invention of the wheel", and today we are about to advance to the Industrial level 4.0, where machines can work, talk, think and...

6 minutes read.

How To Print Colored Text in Python

Changing the colour of certain parts of a string when printing the output of a Python programme to the terminal may make it easier to read. We can approach this...

3 minutes read.

Python Namespace

In python, the namespace is a very important concept that should be understood before using any function or variables. When we write code, we often use variables, libraries, functions, modules, etc....

4 minutes read.

Python eval() function

Python eval() function The eval() function in Python is used to evaluate the given expression. If the specified expression is a legal Python statement, it will be executed. Syntax eval(expression, globals=None, locals=None) Parameter expression: This parameter represents a String,...

1 minute read.

GUI to extract lyrics from a song Using Tkinter in Python

GUI: A graphical interface (GUI) is a user interface that lets users interact with electronic devices like computers and smartphones by using menus, icons, and other visual cues (graphics). In contrast...

4 minutes read.

Python String startswith() method

Python String startswith() method The string.startswith() method in Python returns a boolean value ‘True’ if the given string starts with the prefix, otherwise it returns False. Syntax startswith(prefix[, start[, end]]) Parameter prefix: This parameter signifies the value to check. start(optional):...

1 minute read.

Image to NumPy Arrays in Python

Image is a simple process of working model confined to machine learning, Python works with the image in the data format of width and height i.e. Images are excelled into...

3 minutes read.

Imread Python

In this walkthrough, we'll go over the specifics of using the imread() method of OpenCV-Python and various methods for loading images. Imread is an Image reading library. One of the most helpful...

7 minutes read.

Python Super function

The super function is used to access and call the methods or functions involved in the parent class during Inheritance. What is Inheritance? The process where the parent class inherits some of...

3 minutes read.