Zerodivisionerror integer division or modulo by zero питон ошибка

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

How to Make Division by Zero to Zero in Python?

Wrap it in try-except

The above code can be reduced to:

Reproducing the error

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:

  1. ZeroDivisionError: division by zero
  2. ZeroDivisionError: float division by zero
  3. ZeroDivisionError: integer division or modulo by zero
  4. ZeroDivisionError: long division or modulo by zero
  5. ZeroDivisionError: complex division by zero
  1. SyntaxError- EOL while scanning string literal
  2. TypeError: Can’t convert ‘int’ object to str implicitly
  3. IndentationError: expected an indented block
  4. ValueError: invalid literal for int() with base 10
  5. IndexError: list index out of range : Python
  6. AttributeError: ‘module’ object has no attribute ‘main’
  7. UnboundLocalError: local variable referenced before assignment
  8. TypeError: string indices must be integers
  9. FileNotFoundError: [Errno 2] No such file or directory
  10. Fatal error: Python.h: No such file or directory
  11. ImportError: No module named requests | Python
  12. TypeError: ‘NoneType’ object is not iterable
  13. SyntaxError: unexpected EOF while parsing | Python
  14. zsh: command not found: python
  15. Unicodeescape codec can’t decode bytes in position 2-3
Читайте также:  Woocommerce php product image

Источник

Обработка исключений в Python

Что вы предпринимаете, когда с работой вашей программы что-то идет не так? Допустим, вы пытаетесь открыть файл, но вы ввели неверный путь, или вы хотите узнать информацию у пользователей и они пишут какую-то бессмыслицу. Вы не хотите, чтобы ваша программа крэшилась, по-этому вы выполняете обработку исключений. В Пайтоне, конструкция всегда обернута в то, что называется try/except. В данном разделе мы рассмотрим следующие понятия:

  • Базовые типы исключений;
  • Обработка исключений при помощи try/except;
  • Узнаем, как работает try/except/finally;
  • Выясним, как работает оператор else совместно с try/except;

Начнем со знакомства с самыми обычными исключениями, которые вы увидите в Пайтоне. Обратите внимание на то, что ошибка и исключение – два разных слова, описывающие одно и то же, в контексте обработки исключений.

Основные исключения

Вы уже сталкивались со множеством исключений. Ниже изложен список основных встроенных исключений (определение в документации к Пайтону):

  • Exception – то, на чем фактически строятся все остальные ошибки;
  • AttributeError – возникает, когда ссылка атрибута или присвоение не могут быть выполнены;
  • IOError – возникает в том случае, когда операция I/O (такая как оператор вывода, встроенная функция open() или метод объекта-файла) не может быть выполнена, по связанной с I/O причине: «файл не найден», или «диск заполнен», иными словами.
  • ImportError – возникает, когда оператор import не может найти определение модуля, или когда оператор не может найти имя файла, который должен быть импортирован;
  • IndexError – возникает, когда индекс последовательности находится вне допустимого диапазона;
  • KeyError – возникает, когда ключ сопоставления (dictionary key) не найден в наборе существующих ключей;
  • KeyboardInterrupt – возникает, когда пользователь нажимает клавишу прерывания(обычно Delete или Ctrl+C);
  • NameError – возникает, когда локальное или глобальное имя не найдено;
  • OSError – возникает, когда функция получает связанную с системой ошибку;
  • SyntaxError — возникает, когда синтаксическая ошибка встречается синтаксическим анализатором;
  • TypeError – возникает, когда операция или функция применяется к объекту несоответствующего типа. Связанное значение представляет собой строку, в которой приводятся подробные сведения о несоответствии типов;
  • ValueError – возникает, когда встроенная операция или функция получают аргумент, тип которого правильный, но неправильно значение, и ситуация не может описано более точно, как при возникновении IndexError;
  • ZeroDivisionError – возникает, когда второй аргумент операции division или modulo равен нулю;

Существует много других исключений, но вы вряд ли будете сталкиваться с ними так же часто. В целом, если вы заинтересованы, вы можете узнать больше о них в документации Пайтон.

Как обрабатывать исключения?

Обработка исключений в Пайтон – это очень просто. Потратим немного времени и напишем несколько примеров, которые их вызовут. Мы начнем с одной из самых элементарных проблем: деление на ноль.

Читайте также:  Write lists to file python

Источник

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.

Traceback (most recent call last): File "/Users/python/Desktop/test.py", line 3, in c=a/b; ZeroDivisionError: integer division or modulo by zero [Finished in 0.1s with exit code 1]

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.

ZeroDivisionError: integer division or modulo by zero ZeroDivisionError: long division or modulo by zero ZeroDivisionError: float division by zero ZeroDivisionError: complex division by zero ZeroDivisionError: division by zero

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.

a = 8 b = 0 c = a / b print c

Output

Traceback (most recent call last): File "C:\Users\User\Desktop\python.py", line 3, in c = a / b ZeroDivisionError: division by zero
Traceback (most recent call last): File "/Users/python/Desktop/test.py", line 3, in c = a / b ZeroDivisionError: integer division or modulo by zero [Finished in 0.0s with exit code 1]

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.

a = 8 b = 0 c = ( a / b ) if b != 0 else 0 print c

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.

try: a = 8 b = 0 c = a / b except ZeroDivisionError: c = 0 print c

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.

a = 8 b = 0 if b == 0: c = 0 else: c = a / b print c 

Источник

Читайте также:  Error loading python dll python38 dll

How to Fix ZeroDivisionError in Python

How to Fix ZeroDivisionError in Python

In Python, a ZeroDivisionError is raised when a division or modulo operation is attempted with a denominator or divisor of 0.

What Causes ZeroDivisionError

A ZeroDivisionError occurs in Python when a number is attempted to be divided by zero. Since division by zero is not allowed in mathematics, attempting this in Python code raises a ZeroDivisionError .

Python ZeroDivisionError Example

Here’s an example of a Python ZeroDivisionError thrown due to division by zero:

In this example, a number a is attempted to be divided by another number b , whose value is zero, leading to a ZeroDivisionError :

File "test.py", line 3, in print(a/b) ZeroDivisionError: division by zero 

How to Fix ZeroDivisionError in Python

The ZeroDivisionError can be avoided using a conditional statement to check for a denominator or divisor of 0 before performing the operation.

The code in the earlier example can be updated to use an if statement to check if the denominator is 0:

a = 10 b = 0 if b == 0: print("Cannot divide by zero") else: print(a/b) 

Running the above code produces the correct output as expected:

A try-except block can also be used to catch and handle this error if the value of the denominator is not known beforehand:

try: a = 10 b = 0 print(a/b) except ZeroDivisionError as e: print("Error: Cannot divide by zero") 

Surrounding the code in try-except blocks like the above allows the program to continue execution after the exception is encountered:

Error: Cannot divide by zero 

Track, Analyze and Manage Errors With Rollbar

Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Python errors easier than ever. Try it today!

Источник

Оцените статью