Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Divide By Zero Error

I have a Class in python, with the following attributes:

    self.number1 = 0
    self.number2 = 0
    self.divided = self.number1/self.number2

This of course throws up the zero error:

ZeroDivisionError: integer division or modulo by zero

The idea is that I will increment number1 and number2 later on, but will self.divided be automatically updated? If it is auto updated then how do I get around the zero error? Thanks.

like image 660
eamon1234 Avatar asked Nov 30 '12 13:11

eamon1234


People also ask

How do you fix division by zero in Python?

The Python "ZeroDivisionError: float division by zero" occurs when we try to divide a floating-point number by 0 . To solve the error, use an if statement to check if the number you are dividing by is not zero, or handle the error in a try/except block.

Is division by zero a runtime error in Python?

Division by zero is a logic software bug that in most cases causes a run-time error when a number is divided by zero.

What kind of error is dividing by zero?

Hence, if any number is divided by zero, we get the arithmetic exception .

Why is divide by zero a runtime error?

The divide error messages happen when the computer or software attempts run a process that performs a mathematical division by zero, which is an illegal operation. This error message could also be caused by a computer or software limitation or conflict with computer memory.


1 Answers

No, self.divided is a simple attribute and will not automatically update. For dynamic attributes, use a property instead:

class Foo(object):
    number1 = 0
    number2 = 0

    @property
    def divided(self):
        return self.number1 / self.number2
like image 76
Martijn Pieters Avatar answered Sep 28 '22 10:09

Martijn Pieters