By Lenin Mishra
in
python
—
Jan 15, 2022
Handling Zero Division exceptions in Python
A ZeroDivisionError
is raised when you try to divide by 0. This is part of the ArithmeticError Exception class.
Example 1
Code/Output
# integers
1/0
>>> ZeroDivisionError: division by zero
# floats
5.3/0
>>> ZeroDivisionError: float division by zero
# complex numbers
(1+2j)/0
>>> ZeroDivisionError: complex division by zero
Example 2 — decimal library
If you are working with a decimal library and you perform the division operation with a 0
, you get a DivisionByZero
error.
The DivisionByZero
eexception is decimal
libraries own exception type that derives from the ZeroDivisionError
exception.
Code
from decimal import Decimal
x = Decimal(1)
print(x/0)
Output
decimal.DivisionByZero: [<class 'decimal.DivisionByZero'>]
Handling ZeroDivisionError in Python
You can handle ZeroDivisionError
errors by using the same exception class in your except block.
Code
# integers
try:
1/0
except ZeroDivisionError as e:
print(e)
# floats
try:
5.3/0
except ZeroDivisionError as e:
print(e)
# complex numbers
try:
(1+2j)/0
except ZeroDivisionError as e:
print(e)
Output
division by zero
float division by zero
complex division by zero
Hierarchy of ZeroDivisionError
The ZeroDivisionError
inherits from the ArithmeticError
class, which in turn inherits from the generic Exception
class.
->Exception
-->ArithmeticError
--->ZeroDivisionError
So you can catch all ZeroDivisionError
exceptions using the ArithmeticError
exception class too.
Code
# integers
try:
1/0
except ArithmeticError as e:
print(e, e.__class__)
# floats
try:
5.3/0
except ArithmeticError as e:
print(e, e.__class__)
# complex numbers
try:
(1+2j)/0
except ArithmeticError as e:
print(e, e.__class__)
Output
division by zero <class 'ZeroDivisionError'>
float division by zero <class 'ZeroDivisionError'>
complex division by zero <class 'ZeroDivisionError'>
Check out other Python Built-in Exception classes in Python.
While programming, you may have experienced the ZeroDivisionError: Division by zero in Python. There are a few suggestions that can help you resolve this error. Read the following article to understand more.
What causes the ZeroDivisionError: division by zero in Python?
You must know that in math, a positive number, a negative number divided by zero, will return undefined results.
ZeroDivisionError: this is a built-in exception that will appear when a number is divisible. Note that you always handle the ZeroDivisionError exception, so your program doesn’t terminate.
The ZeroDivisionError: division by zero happens when you divide a float by 0.
Example:
myNumber1 = 18.0 myNumber2 = 0 print(myNumber1 / myNumber2)
Output:
Traceback (most recent call last):
File "code.py", line 4, in <module>
print(myNumber1 / myNumber2)
ZeroDivisionError: float division by zero
How to solve this error?
Use a try/except block
You can use the try-except block to handle the error.
Example:
- Initialize two variables (the second variable has a value of 0).
- The code between the first try-except clause is executed. If no exception occurs, only the try clause will run. The except clause will not run. If a ZeroDivisionError exception occurs, only the except clause runs.
myNumber1 = 18.0 myNumber2 = 0 # Use a try/except block to ignore errors try: result = myNumber1 / myNumber2 print(result) except ZeroDivisionError: print("Change the value of myNumber2. Enter a value that is not 0")
Output:
Change the value of myNumber2. Enter a value that is not 0
Use != operator
You can use the relational operator ‘!=’ for error handling.
The ‘!=’ operator compares the values of the arguments: if they are different, it returns True. If equal, returns False.
Example:
- Initialize two variables (the second variable has a value of 0).
- Use the ‘!=’ operator compares ‘myNumber2’ with 0. Otherwise, execute the statement in the if. If zero, execute the statement in else.
myNumber1 = 18.0 myNumber2 = 0 # Use the '!=' operator compares 'myNumber2' with 0 if myNumber2 != 0: result = myNumber1 / myNumber2 print(result) else : print ("Change the value of myNumber2. Enter a value that is not 0")
Output:
Change the value of myNumber2. Enter a value that is not 0
Summary
This article will help you if you encounter the ZeroDivisionError: division by zero in Python. If you have any questions about this issue, leave a comment below. I will answer your questions. Thanks for reading!
Maybe you are interested:
- TypeError: can only concatenate list (not “str”) to list
- SyntaxError: leading zeros in decimal integer literals are not permitted in python
My name is Jason Wilson, you can call me Jason. My major is information technology, and I am proficient in C++, Python, and Java. I hope my writings are useful to you while you study programming languages.
Name of the university: HHAU
Major: IT
Programming Languages: C++, Python, Java
To solve ZeroDivisionError: division by zero, use the try-except statement. The try block lets you test a block of code for errors. The except block enables you to handle the error.
ZeroDivisionError is a built-in Python exception thrown when a number is divided by 0. As a common mathematics rule, a number divided by 0 is infinity. Therefore, this error may cause even when a number is modulo by 0. The ZeroDivisionError can be handled by exception handlers.
We can put the block of code that can cause an error into the try block and test the code. For example, in the exception block name, the exception is ZeroDivisionError the exception will be executed if the number is divided by zero.
Example
a = int(input("enter the value for a: "))
b = int(input("enter the value for b: "))
c = a / b
print(c)
Output
enter the value for a: 10
enter the value for b: 0
Traceback (most recent call last):
File "/Users/krunallathiya/Desktop/Code/R/data.py", line 4, in <module>
c = a / b
ZeroDivisionError: division by zero
In this example, let us consider the value for variable a = 10 and the value for b = 0. When the program gets executed, the error is raised. The error raised is called the ZeroDivisionError.
If the value of b is given as 2, the program would have executed successfully. Even when the value of a is 0, the program works fine and prints 0 as output.
But if we pass b = 0, it creates an error. Only during division operation is performed is this error raised.
Solve ZeroDivisionError: division by zero using if
Use the if statement to solve the ZeroDivisionError in Python. You can check the value of the denominator using the if statement if you divide a number by a denominator value. If the denominator value is zero, we execute the else statement; otherwise, it will execute the if statement.
a = int(input("enter the value for a: "))
b = int(input("enter the value for b: "))
if(b > 0):
c = a / b
print(c)
else:
print("The value of b should be greater than 0")
Output
enter the value for a: 10
enter the value for b: 0
The value of b should be greater than 0
Use try-except to solve ZeroDivisionError
The try-except approach can be used to handle the exception. The ZeroDivisionError occurs when we divide numbers and find the denominator 0.
Using the try-except approach, we are putting division code inside the try block, and if it finds an exception, then except block will be executed.
a = int(input("enter the value for a: "))
b = int(input("enter the value for b: "))
try:
c = a / b
except ZeroDivisionError:
print("The value of b should not be equal to 0 please change the value for b")
c = 0
print(c)
Output
enter the value for a: 10
enter the value for b: 0
The value of b should not be equal to 0 please change the value for b
0
If you encounter ZeroDivisionError in Python, it suggests that there is a number dividing by zero or the denominator’s value is zero. To handle this exception, use the try-except block and handle the exception, and you can set the output as 0, which is optional.
That’s it for this tutorial.
See also
Only size-1 arrays can be converted to Python scalars
Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Data Science and Machine Learning, and he is an expert in R Language. Krunal has experience with various programming languages and technologies, including PHP, Python, and JavaScript. He is comfortable working in front-end and back-end development.
Содержание
- ZeroDivisionError: float division | Python
- ZeroDivisionError
- Handling ZeroDivisionError in Python
- Reproducing the error
- Output:
- Wrap it in try except
- Check before you do the division
- Different Variation
- Zero division error float division
- ZeroDivisionError: float division by zero in Python #
- Conclusion #
- ZeroDivisionError: division by zero
- Different Variation of the error
- Root Cause
- How to reproduce this issue
- Output
- Solution 1
- Output
- Solution 2
- Output
- Solution 3
- Exceptions and Testing¶
- Exceptions¶
- Extending the logic¶
- Exceptions in your own code¶
- Testing¶
- Formalizing tests¶
- Test Driven Development¶
ZeroDivisionError: float division | Python
In mathematics, any non-zero number either positive or negative divided by zero is undefined because there is no value. The reason is that the result of a division by zero is undefined is the fact that any attempt at a definition leads to a contradiction.
ZeroDivisionError
The super class of ZeroDivisionError is ArithmeticError. ZeroDivisionError is a built-in Python exception thrown when a number is divided by 0. This means that the exception raised when the second argument of a division or modulo operation is zero. In Mathematics, when a number is divided by a zero, the result is an infinite number. It is impossible to write an Infinite number physically. Python interpreter throws «ZeroDivisionError» error if the result is infinite number. While implementing any program logic and there is division operation make sure always handle ArithmeticError or ZeroDivisionError so that program will not terminate.
Handling ZeroDivisionError in Python
The above code can be reduced to:
Reproducing the error
Output:
You can solve the ZeroDivisionError by the following ways:
Wrap it in try except
Check before you do the division
The above code can be reduced to:
Different Variation
In Python, the Zero Division Error:division by zero is thrown in various forms in different contexts. They are given below:
- ZeroDivisionError: division by zero
- ZeroDivisionError: float division by zero
- ZeroDivisionError: integer division or modulo by zero
- ZeroDivisionError: long division or modulo by zero
- ZeroDivisionError: complex division by zero
Источник
Zero division error float division
Reading time В· 2 min
ZeroDivisionError: float 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.
Here is an example of how the error occurs.
It’s unclear what value is expected when we divide by 0 , so Python throws an error.
When we divide a number by 0 , the result tends towards infinity.
One way to solve the error is to check if the value we are dividing by is not 0 .
We check if the b variable doesn’t store a 0 value and if it doesn’t, we divide a by b .
If setting the result variable to 0 , if b is equal to 0 suits your use case, you can shorten this to a single line.
The expression x and y first evaluates x , and if x is falsy, its value is returned, otherwise, y is returned.
Alternatively, you can use a try/except statement.
We try to divide a by b and if we get a ZeroDivisionError , the except block sets the result variable to 0 .
The best way to solve the error is to figure out where the variable gets assigned a 0 and check whether that’s the expected behavior.
Here are some common ways you might get a zero value unexpectedly.
Conclusion #
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.
Источник
ZeroDivisionError: division by zero
ZeroDivisionError occurs when a number is divided by a zero. In Mathematics, when a number is divided by a zero, the result is an infinite number. It is impossible to write an Infinite number physically. Python interpreter throws “ZeroDivisionError: division by zero” error if the result is infinite number.
You can divide a number by another number. The division operation divides a number into equal parts or groups. Dividing a number into zero pieces or zero groups is meaning less. In mathematics, dividing a number by zero is undefined.
If a number is divided by zero, the result wil be infinite number. Python can not handle the infinite number because the infinite number is difficult to write in concrete form. In this case, Python throws “ZeroDivisionError: division by zero”. The error would be thrown as like below.
Different Variation of the error
In different contexts the Zero Division Error-division by zero is thrown in various forms in python. The numerous variations of ZeroDivisionError are given below.
Root Cause
The zero division error is due to either a number being divided by zero, or a number being modulo by zero. The denominator of the division operation should be a non zero numeric value. If the demonimator is zero then ZeroDivisionError will be thrown by python interpreter.
Dividing a number into zero pieces or zero groups does not make sense. The result is infinite number not representable in python. Therefore, python throws “ZeroDivisionError: integer division or modulo by zero”. This error occurs for all numbers such as integer, long, float and complex number
How to reproduce this issue
A number must be divided by an another non zero number. Python interpreter will throw ZeroDivisionError if you create a simple program with a number divided by zero. If the division denominator is set to zero, then this error will occur.
The example code below shows how this issue can be reproduced.
Output
Solution 1
Python can not divide a number by zero. Before doing a division or modulo operation, the denominator must be verified for nonzero. The code below shows how to handle a denominator when it is zero.
Output
Solution 2
If the program is not sure of the denominator value, the denominator value may be zero in some rare cases. In this case, handle the ZeroDivisionError when it occurs. The example below shows how to handle the exception of ZeroDivisionError in the code.
Output
Solution 3
In the program, if the denominator is zero, the output of the division operation can be set to zero. Mathematically, this may not be correct. Setting zero for the division operation will solve this issue in real-time calculation. The following code shows how to set the zero for the division operation.
Источник
Exceptions and Testing¶
Things go wrong when programming all the time. Some of these “problems” are errors that stop the program from making sense. Others are problems that stop the program from working in specific, special cases. These “problems” may be real, or we may want to treat them as special cases that don’t stop the program from running.
These special cases can be dealt with using exceptions.
Exceptions¶
Let’s define a function that divides two numbers.
But what happens if we try something really stupid?
So, the code works fine until we pass in input that we shouldn’t. When we do, this causes the code to stop. To show how this can be a problem, consider the loop:
There are three sensible results, but we only get the first.
There are many more complex, real cases where it’s not obvious that we’re doing something wrong ahead of time. In this case, we want to be able to try running the code and catch errors without stopping the code. This can be done in Python:
The idea here is given by the names. Python will try to execute the code inside the try block. This is just like an if or a for block: each command that is indented in that block will be executed in order.
If, and only if, an error arises then the except block will be checked. If the error that is produced matches the one listed then instead of stopping, the code inside the except block will be run instead.
To show how this works with different errors, consider a different silly error:
We see that, as it makes no sense to divide by a string, we get a TypeError instead of a ZeroDivisionError . We could catch both errors:
We could catch any error:
This doesn’t give us much information, and may lose information that we need in order to handle the error. We can capture the exception to a variable, and then use that variable:
Here we have caught two possible types of error within the tuple (which must, in this case, have parantheses) and captured the specific error in the variable exception . This variable can then be used: here we just print it out.
Normally best practise is to be as specific as possible on the error you are trying to catch.
Extending the logic¶
Sometimes you may want to perform an action only if an error did not occur. For example, let’s suppose we wanted to store the result of dividing 4 by a divisor, and also store the divisor, but only if the divisor is valid.
One way of doing this would be the following:
The statements in the else block are only run if the try block succeeds. If it doesn’t — if the statements in the try block raise an exception — then the statements in the else block are not run.
Exceptions in your own code¶
Sometimes you don’t want to wait for the code to break at a low level, but instead stop when you know things are going to go wrong. This is usually because you can be more informative about what’s going wrong. Here’s a slightly artificial example:
It should be obvious to the code that this is going to go wrong. Rather than letting the code hit the ZeroDivisionError exception automatically, we can raise it ourselves, with a more meaningful error message:
There are a large number of standard exceptions in Python, and most of the time you should use one of those, combined with a meaningful error message. One is particularly useful: NotImplementedError .
This exception is used when the behaviour the code is about to attempt makes no sense, is not defined, or similar. For example, consider computing the roots of the quadratic equation, but restricting to only real solutions. Using the standard formula
we know that this only makes sense if . We put this in code as:
Testing¶
How do we know if our code is working correctly? It is not when the code runs and returns some value: as seen above, there may be times where it makes sense to stop the code even when it is correct, as it is being used incorrectly. We need to test the code to check that it works.
Unit testing is the idea of writing many small tests that check if simple cases are behaving correctly. Rather than trying to prove that the code is correct in all cases (which could be very hard), we check that it is correct in a number of tightly controlled cases (which should be more straightforward). If we later find a problem with the code, we add a test to cover that case.
Consider a function solving for the real roots of the quadratic equation again. This time, if there are no real roots we shall return None (to say there are no roots) instead of raising an exception.
First we check what happens if there are imaginary roots, using :
As we wanted, it has returned None . We also check what happens if the roots are zero, using :
We get the expected behaviour. We also check what happens if the roots are real, using which has roots
:
Something has gone wrong. Looking at the code, we see that the x_minus line has been copied and pasted from the x_plus line, without changing the sign correctly. So we fix that error:
We have changed the code, so now have to re-run all our tests, in case our change broke something else:
As a final test, we check what happens if the equation degenerates to a linear equation where , using
with solution
:
In this case we get an exception, which we don’t want. We fix this problem:
And we now must re-run all our tests again, as the code has changed once more:
Formalizing tests¶
This small set of tests covers most of the cases we are concerned with. However, by this point it’s getting hard to remember
- what each line is actually testing, and
- what the correct value is meant to be.
To formalize this, we write each test as a small function that contains this information for us. Let’s start with the case where the roots are
:
What this function does is checks that the results of the function call match the expected value, here stored in roots . If it didn’t match the expected value, it would raise an exception:
Testing that one floating point number equals another can be dangerous. Consider with roots
:
We see that the solutions match to the first 14 or so digits, but this isn’t enough for them to be exactly the same. In this case, and in most cases using floating point numbers, we want the result to be “close enough”: to match the expected precision. There is an assertion for this as well:
The assert_allclose statement takes options controlling the precision of our test.
We can now write out all our tests:
We now have a set of tests — a testsuite, as it is sometimes called — encoded in functions, with meaningful names, which give useful error messages if the test fails. Every time the code is changed, we want to re-run all the tests to ensure that our change has not broken the code. This can be tedious. A better way would be to run a single command that runs all tests. nosetests is that command.
The easiest way to use it is to put all tests in the same file as the function being tested. So, create a file quadratic.py containing
Then, in a terminal or command window, switch to the directory containing this file. Then run
You should see output similar to
Each dot corresponds to a test. If a test fails, nose will report the error and move on to the next test. nose automatically runs every function that starts with test , or every file in a module starting with test , or more. The documentation gives more details about using nose in more complex cases.
To summarize: when trying to get code working, tests are essential. Tests should be simple and cover as many of the easy cases and as much of the code as possible. By writing tests as functions that raise exceptions, and using a testing framework such as nose , all tests can be run rapidly, saving time.
Test Driven Development¶
There are many ways of writing code to solve problems. Most involve planning in advance how the code should be written. An alternative is to say in advance what tests the code should pass. This Test Driven Development (TDD) has advantages (the code always has a detailed set of tests, features in the code are always relevant to some test, it’s easy to start writing code) and some disadvantages (it can be overkill for small projects, it can lead down blind alleys). A detailed discussion is given by Beck’s book, and a more recent discussion in this series of conversations.
Even if TDD does not work for you, testing itself is extremely important.
Источник
Ивванн 1 / 1 / 0 Регистрация: 12.10.2017 Сообщений: 220 |
||||
1 |
||||
18.10.2019, 13:41. Показов 17221. Ответов 4 Метки нет (Все метки)
Есть код. Как исправить эту ошибку?
__________________
0 |
1302 / 842 / 409 Регистрация: 12.03.2018 Сообщений: 2,305 |
|
18.10.2019, 13:48 |
2 |
Как исправить эту ошибку? Перестать нарушать законы школьной математики
1 |
1 / 1 / 0 Регистрация: 12.10.2017 Сообщений: 220 |
|
18.10.2019, 13:49 [ТС] |
3 |
ioprst, а можете помочь исправить?
0 |
1302 / 842 / 409 Регистрация: 12.03.2018 Сообщений: 2,305 |
|
18.10.2019, 13:53 |
4 |
на первой итерации znamennyk = znamennyk * (i*2) = 0, т.к. i=0 => на следующей итерации znamennyk = znamennyk * (i*2-1) = 0, т.к. znamennyk = 0 =>chuselnuk/znamennyk приводит к ошибке
ioprst, а можете помочь исправить? Нет, т.к. задачу вашу не знаю. Очевидно, что ошибка в алгоритме.
0 |
PyDev 36 / 21 / 9 Регистрация: 17.10.2019 Сообщений: 95 |
||||||||
18.10.2019, 14:36 |
5 |
|||||||
Выдает 0:
В 16 строке Добавлено через 6 минут
0 |