Integer division or modulo by zero python ошибка

I am new to doing simple math using python, so sorry if this is a silly question.

I have 8 variables that are all set to integers and these integers are used when performing a simple calculation.

a = 0
b = 17
c = 152
d = 1
e = 133
f = 19
g = 20
h = 0

answer = ( ( ( a / f ) + b + c ) - ( g + ( h / f ) ) ) / ( d / f )

print answer

When I run this code, I get the error, ZeroDivisionError: integer division or modulo by zero.

I have read about this error and all documentation points towards my divisor being zero, but if I print this with the numbers as strings in place of the variables, I get:

( ( ( 0 / 19 ) + 17 + 152 ) - ( 20 + ( 0 / 19 ) ) ) / ( 1 / 19 )

Nowhere in this statement is the divisor zero.

Please let me know how I need to change my expression in order to get the answer 2831. Note that I can change the type of the variables to a float or other. Thank you for your help!

asked Jan 29, 2013 at 8:46

ccdpowell's user avatar

Probably you are using Python 2.x, where x / y is an integer division.

So, in the below code: —

( 20 + ( 0 / 19 ) ) ) / ( 1 / 19 )

1 / 19 is an integer division, which results in 0. So the expression is essentially same as: —

( 20 + ( 0 / 19 ) ) ) / 0

Now you see where the error comes from.


You can add following import in you python code, to enforce floating-point division: —

from __future__ import division

Or you could cast one of the integers to a float, using either float() or just by adding .0 to the initial value.

SuperBiasedMan's user avatar

answered Jan 29, 2013 at 8:48

Rohit Jain's user avatar

Rohit JainRohit Jain

209k45 gold badges406 silver badges523 bronze badges

0

from __future__ import division

and than do your calculation

it will cause the division to return floats

answered Jan 29, 2013 at 8:48

YardenST's user avatar

YardenSTYardenST

5,0792 gold badges32 silver badges53 bronze badges

This should work. Here’s my code:

a = 0
b = 17
c = 152
d = 1
e = 133
f = 19
g = 20
h = 0

answer = ( ( ( a / f ) + b + c ) - ( g + ( h / f ) ) ) / ( d / f )

print(answer)

Nearly exactly same.

answered Mar 5, 2019 at 21:34

user11156442's user avatar

Что вы предпринимаете, когда с работой вашей программы что-то идет не так? Допустим, вы пытаетесь открыть файл, но вы ввели неверный путь, или вы хотите узнать информацию у пользователей и они пишут какую-то бессмыслицу. Вы не хотите, чтобы ваша программа крэшилась, по-этому вы выполняете обработку исключений. В Пайтоне, конструкция всегда обернута в то, что называется 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 равен нулю;

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

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

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

1 / 0

Traceback (most recent call last):

    File «<string>», line 1, in <fragment>

ZeroDivisionError: integer division or modulo by zero

try:

    1 / 0

except ZeroDivisionError:

    print(«You cannot divide by zero!»)

Если мы обратимся к урокам элементарной математики, то вспомним, что на ноль делить нельзя. В Пайтоне данная операция вызовет ошибку, как мы можем видеть в примере выше. Чтобы поймать ошибку, мы завернем операцию в оператор try/except.

«Голое» исключение

Есть еще один способ поймать ошибку:

try:

    1 / 0

except:

    print(«You cannot divide by zero!»)

Но мы его не рекомендуем. На жаргоне Пайтона, это известно как голое исключение, что означает, что будут найдены вообще все исключения. Причина, по которой так делать не рекомендуется, заключается в том, что вы не узнаете, что именно за исключение вы выловите. Когда у вас возникло что-то в духе ZeroDivisionError, вы хотите выявить фрагмент, в котором происходит деление на ноль. В коде, написанном выше, вы не можете указать, что именно вам нужно выявить. Давайте взглянем еще на несколько примеров:

my_dict = {«a»:1, «b»:2, «c»:3}

try:

    value = my_dict[«d»]

except KeyError:

    print(«That key does not exist!»)

my_list = [1, 2, 3, 4, 5]

try:

    my_list[6]

except IndexError:

    print(«That index is not in the list!»)

В первом примере, мы создали словарь из трех элементов. После этого, мы попытались открыть доступ ключу, которого в словаре нет. Так как ключ не в словаре, возникает KeyError, которую мы выявили. Второй пример показывает список, длина которого состоит из пяти объектов. Мы попытались взять седьмой объект из индекса.

Есть вопросы по Python?

На нашем форуме вы можете задать любой вопрос и получить ответ от всего нашего сообщества!

Telegram Чат & Канал

Вступите в наш дружный чат по Python и начните общение с единомышленниками! Станьте частью большого сообщества!

Паблик VK

Одно из самых больших сообществ по Python в социальной сети ВК. Видео уроки и книги для вас!

Помните, что списки в Пайтоне начинаются с нуля, так что когда вы говорите 6, вы запрашиваете 7. В любом случае, в нашем списке только пять объектов, по этой причине возникает IndexError, которую мы выявили. Вы также можете выявить несколько ошибок за раз при помощи одного оператора. Для этого существует несколько различных способов. Давайте посмотрим:

my_dict = {«a»:1, «b»:2, «c»:3}

try:

    value = my_dict[«d»]

except IndexError:

    print(«This index does not exist!»)

except KeyError:

    print(«This key is not in the dictionary!»)

except:

    print(«Some other error occurred!»)

Это самый стандартный способ выявить несколько исключений. Сначала мы попробовали открыть доступ к несуществующему ключу, которого нет в нашем словаре. При помощи try/except мы проверили код на наличие ошибки KeyError, которая находится во втором операторе except. Обратите внимание на то, что в конце кода у нас появилась «голое» исключение. Обычно, это не рекомендуется, но вы, возможно, будете сталкиваться с этим время от времени, так что лучше быть проинформированным об этом. Кстати, также обратите внимание на то, что вам не нужно использовать целый блок кода для обработки нескольких исключений. Обычно, целый блок используется для выявления одного единственного исключения. Изучим второй способ выявления нескольких исключений:

try:

    value = my_dict[«d»]

except (IndexError, KeyError):

    print(«An IndexError or KeyError occurred!»)

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

В зависимости от сложности данной ошибки, вам может понадобиться выйти из программы. Иногда вам может понадобиться выполнить очистку, перед выходом из программы. Например, если вы открыли соединение с базой данных, вам нужно будет закрыть его, перед выходом из программы, или вы можете закончить с открытым соединением. Другой пример – закрытие дескриптора файла, к которому вы обращаетесь. Теперь нам нужно научиться убирать за собой. Это очень просто, если использовать оператор finally.

Оператор finally

Оператор finally очень прост в использовании. Давайте взглянем на нижеизложенный пример:

my_dict = {«a»:1, «b»:2, «c»:3}

try:

    value = my_dict[«d»]

except KeyError:

    print(«A KeyError occurred!»)

finally:

    print(«The finally statement has executed!»)

Если вы запустите это код, оно отобразиться и в операторе except и в finally. Весьма просто, не так ли? Теперь вы можете использовать оператор finally, чтобы убрать за собой. Вы можете также вписать код exit в конце оператора finally.

Попробуйте except или else

Оператор try/except также имеет пункт else. Он работает только в том случае, если в вашем коде нет ни единой ошибки. Давайте потратим немного времени и взглянем на парочку примеров:

my_dict = {«a»:1, «b»:2, «c»:3}

try:

    value = my_dict[«a»]

except KeyError:

    print(«A KeyError occurred!»)

else:

    print(«No error occurred!»)

Мы видим словарь, состоящий из трех элементов, и в операторе try/except мы открываем доступ к существующему ключу. Это работает, так что ошибка KeyError не возникает. Так как ошибки нет, else работает, и надпись“No error occurred!” появляется на экране. Теперь добавим оператор finally:

my_dict = {«a»:1, «b»:2, «c»:3}

try:

    value = my_dict[«a»]

except KeyError:

    print(«A KeyError occurred!»)

else:

    print(«No error occurred!»)

finally:

    print(«The finally statement ran!»)

В данном коде работают и оператор else и finally. Большую часть времени вы не будете сталкиваться с оператором else, используемый в том или ином коде, который следует за оператором try/except, если ни одна ошибка не была найдена. Единственное полезное применение оператора else, которое я видел, это когда вы хотите запустить вторую часть кода, в которой может быть ошибка. Конечно, если ошибка возникает в else, то она не будет поймана.

Подведем итоги

Теперь вы можете выявлять исключения в вашем коде. Если вы обнаружили, что в вашем коде есть ошибка, то теперь вы знаете, как выявить её и спокойно выйти из программы, или продолжить спокойно работать.

Являюсь администратором нескольких порталов по обучению языков программирования Python, Golang и Kotlin. В составе небольшой команды единомышленников, мы занимаемся популяризацией языков программирования на русскоязычную аудиторию. Большая часть статей была адаптирована нами на русский язык и распространяется бесплатно.

E-mail: vasile.buldumac@ati.utm.md

Образование
Universitatea Tehnică a Moldovei (utm.md)

  • 2014 — 2018 Технический Университет Молдовы, ИТ-Инженер. Тема дипломной работы «Автоматизация покупки и продажи криптовалюты используя технический анализ»
  • 2018 — 2020 Технический Университет Молдовы, Магистр, Магистерская диссертация «Идентификация человека в киберпространстве по фотографии лица»

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 <module>
    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:UsersUserDesktoppython.py", line 3, in <module>
    c = a / b
ZeroDivisionError: division by zero
Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    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

0

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

0

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

Output

0

Your loop starts with 0 so this ZeroDivisionError occurs.

exception ZeroDivisionError
Raised when the second argument of a division or modulo operation is zero. The associated value is a string indicating the type of the operands and the operation.[source]

You have to start your for loop from 1

like this: for n in range(1,i+1):

and you don’t have to do while loop this will go infinite.

your code will be:

i = int(input("digite o 1o inteiro positivo: "))
j = int(input("digite o 2o inteiro positivo: "))

# i,j = 9,6 
aux, cont = 1, 0 

if i > j: # 9 < 6
    for n in range (1,i+1): # n = (1,2,3,4,5,6,7,8,9)
        #while n <= i: # (1,2,3,4,5,6,7,8,9)
        if i % n == 0 and j % n == 0: # 9 % (1,3,9) e 6 % (1,3,6)
            print(n) # print(1,3)

or you can also write your code in try-except block, like this which will give the same output:

i = int(input("digite o 1o inteiro positivo: "))
j = int(input("digite o 2o inteiro positivo: "))

# i,j = 9,6 
aux, cont = 1, 0 

if i > j: # 9 < 6
    for n in range (i+1): # n = (1,2,3,4,5,6,7,8,9)
        try:
          if i % n == 0 and j % n == 0: # 9 % (1,3,9) e 6 % (1,3,6)
              print(n) # print(1,3)
        except ZeroDivisionError:
            n+= 1

output

digite o 1o inteiro positivo: 9
digite o 2o inteiro positivo: 6

1
3

Answer by Sloane Leon

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

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 <module>
    c=a/b;
ZeroDivisionError: integer division or modulo by zero
[Finished in 0.1s with exit code 1]

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

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:UsersUserDesktoppython.py", line 3, in <module>
    c = a / b
ZeroDivisionError: division by zero
Traceback (most recent call last):
  File "C:UsersUserDesktoppython.py", line 3, in <module>
    c = a / b
ZeroDivisionError: division by zero
Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 3, in <module>
    c = a / b
ZeroDivisionError: integer division or modulo by zero
[Finished in 0.0s with exit code 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

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

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

Output


Answer by Elian Barajas

2

What value do you want for 1/0? For 0/0, any value at all makes some sense (because x/y==z still implies z**y==x), but for anything else divided by 0, no value makes sense (unless you have an infinite integer, and define infinity*0 == 0).

– abarnert

Apr 24 ’15 at 1:40

,

I am trying to find an online free to use algorithm based grammar checker, that can point out mistakes, reliably. Any suggestions?

,
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
,Please be sure to answer the question. Provide details and share your research!

Catch the error and handle it:

try:
    z = x / y
except ZeroDivisionError:
    z = 0

Or check before you do the division:

if y == 0:
    z = 0
else:
    z = x / y

The latter can be reduced to:

z = 0 if y == 0 else (x / y) 

Or if you’re sure y is a number, which implies it`s truthy if nonzero:

z = (x /y) if y else 0

Answer by Megan Cook

Moving along through our in-depth Python Exception Handling series, today we’ll be looking at the ZeroDivisionError. As you may suspect, the ZeroDivisionError in Python indicates that the second argument used in a division (or modulo) operation was zero.,BaseException

Exception

ArithmeticError

ZeroDivisionError

,Exception

ArithmeticError

ZeroDivisionError

,All Python exceptions inherit from the BaseException class, or extend from an inherited class therein. The full exception hierarchy of this error is:

Below is the full code sample we’ll be using in this article. It can be copied and pasted if you’d like to play with the code yourself and see how everything works.

import decimal
from enum import Enum

from gw_utility.logging import Logging
from mpmath import mpf


class NumberType(Enum):
    """Specifies number type or library used for calculating values."""
    INTEGER = 1
    FLOAT = 2
    DECIMAL = 3
    MPMATH = 4


def main():
    Logging.line_separator("FRACTION TEST", 40, '+')

    divide_test(5, 25)

    Logging.line_separator("WHOLE NUMBER TEST", 40, '+')

    divide_test(25, 5)

    Logging.line_separator("DIVIDE BY ZERO TEST", 40, '+')

    divide_test(5, 0)


def divide_test(denominator, numerator):
    """Perform division tests using all different numeric types and mathematic libraries.

    :param denominator: Denominator.
    :param numerator: Numerator.
    """
    Logging.line_separator('as int')
    Logging.log(divide(denominator, numerator))

    Logging.line_separator('as float')
    Logging.log(divide(denominator, numerator, NumberType.FLOAT))

    Logging.line_separator('as decimal.Decimal')
    Logging.log(divide(denominator, numerator, NumberType.DECIMAL))

    Logging.line_separator('as mpmath.mpf')
    Logging.log(divide(denominator, numerator, NumberType.MPMATH))


def divide(numerator, denominator, lib: NumberType = NumberType.INTEGER):
    """Get result of division of numerator and denominator, using passed numeric type or library.

    :param numerator: Numerator.
    :param denominator: Denominator.
    :param lib: Type of numeric value or library to use for calculation.
    :return: Division result.
    """
    try:
        if lib == NumberType.INTEGER:
            # Divide using standard integer.
            return numerator / denominator
        elif lib == NumberType.FLOAT:
            # Convert to floats before division.
            return float(numerator) / float(denominator)
        elif lib == NumberType.DECIMAL:
            # Divide the decimal.Decimal value.
            return decimal.Decimal(numerator) / decimal.Decimal(denominator)
        elif lib == NumberType.MPMATH:
            # Divide using the mpmath.mpf (real float) value.
            return mpf(numerator) / mpf(denominator)
        else:
            # Divide using standard integer (default).
            return numerator / denominator
    except ZeroDivisionError as error:
        # Output expected ZeroDivisionErrors.
        Logging.log_exception(error)
    except Exception as exception:
        # Output unexpected Exceptions.
        Logging.log_exception(exception, False)


if __name__ == "__main__":
    main()

We start with the NumeerType(Enum), which we’ll use throughout the code to differentiate between the various numeric types and mathematical libraries we’ll be using, including int, float, decimal.Decimal, and mpmath.mpf:

class NumberType(Enum):
    """Specifies number type or library used for calculating values."""
    INTEGER = 1
    FLOAT = 2
    DECIMAL = 3
    MPMATH = 4

Our divide(numerator, denominator, lib: NumberType = NumberType.INTEGER) method is where the majority of our logic and calculations take place:

def divide(numerator, denominator, lib: NumberType = NumberType.INTEGER):
    """Get result of division of numerator and denominator, using passed numeric type or library.

    :param numerator: Numerator.
    :param denominator: Denominator.
    :param lib: Type of numeric value or library to use for calculation.
    :return: Division result.
    """
    try:
        if lib == NumberType.INTEGER:
            # Divide using standard integer.
            return numerator / denominator
        elif lib == NumberType.FLOAT:
            # Convert to floats before division.
            return float(numerator) / float(denominator)
        elif lib == NumberType.DECIMAL:
            # Divide the decimal.Decimal value.
            return decimal.Decimal(numerator) / decimal.Decimal(denominator)
        elif lib == NumberType.MPMATH:
            # Divide using the mpmath.mpf (real float) value.
            return mpf(numerator) / mpf(denominator)
        else:
            # Divide using standard integer (default).
            return numerator / denominator
    except ZeroDivisionError as error:
        # Output expected ZeroDivisionErrors.
        Logging.log_exception(error)
    except Exception as exception:
        # Output unexpected Exceptions.
        Logging.log_exception(exception, False)

The divide_test(denominator, numerator) method performs a series of calls to the divide(...) method above, ensuring we test each of the four different numeric types at least once for each set of passed denominator and numerator pairs:

def divide_test(denominator, numerator):
    """Perform division tests using all different numeric types and mathematic libraries.

    :param denominator: Denominator.
    :param numerator: Numerator.
    """
    Logging.line_separator('as int')
    Logging.log(divide(denominator, numerator))

    Logging.line_separator('as float')
    Logging.log(divide(denominator, numerator, NumberType.FLOAT))

    Logging.line_separator('as decimal.Decimal')
    Logging.log(divide(denominator, numerator, NumberType.DECIMAL))

    Logging.line_separator('as mpmath.mpf')
    Logging.log(divide(denominator, numerator, NumberType.MPMATH))

Alright. Everything is setup so now we’ll perform a few basic tests within our main() method:

def main():
    Logging.line_separator("FRACTION TEST", 40, '+')

    divide_test(5, 25)

    Logging.line_separator("WHOLE NUMBER TEST", 40, '+')

    divide_test(25, 5)

    Logging.line_separator("DIVIDE BY ZERO TEST", 40, '+')

    divide_test(5, 0)

Nothing fancy going on here. We want to perform tests that should result in a fractional (decimal) number, a whole (integer) number, and an attempt to divide by zero. Executing the code above produces the following output:

++++++++++++ FRACTION TEST +++++++++++++
---------------- as int ----------------
0.2
--------------- as float ---------------
0.2
---------- as decimal.Decimal ----------
0.2
------------ as mpmath.mpf -------------
0.2

++++++++++ WHOLE NUMBER TEST +++++++++++
---------------- as int ----------------
5.0
--------------- as float ---------------
5.0
---------- as decimal.Decimal ----------
5
------------ as mpmath.mpf -------------
5.0

+++++++++ DIVIDE BY ZERO TEST ++++++++++
---------------- as int ----------------
[EXPECTED] ZeroDivisionError: division by zero
None
--------------- as float ---------------
[EXPECTED] ZeroDivisionError: float division by zero
None
---------- as decimal.Decimal ----------
[EXPECTED] DivisionByZero: [<class 'decimal.DivisionByZero'>]
None
------------ as mpmath.mpf -------------
[EXPECTED] ZeroDivisionError: 
None

Answer by Jeremiah Duarte

The super class of ZeroDivisionError is ArithmeticError. This exception raised when the second argument of a division or modulo operation is zero. The associated value is a string indicating the type of the operands and the operation. ,Zero Division Error occurred.,ZeroDivisionError : Division by Zero,[Solved]: ZeroDivisionError

num_list=[]
total=0
avg=total/len(num_list)
print("Average:"+avg)

Answer by Kyro Miranda

It is not possible to divide by zero. If we try to do this, a
ZeroDivisionError is raised and the script is interrupted.
,
This is the hierarchy of the KeyboardInterrupt exception.
,
First, we simply check that y value is not zero. If the
y value is zero, we print a warning message and repeat the input
cycle again. This way we handled the error and the script is not interrupted.
,
In this script, we get two numbers from the console. We divide these two numbers.
If the second number is zero, we get an exception.

In Python, we have the following syntax to deal with exceptions:

try:
   # do something

except ValueError:
   # handle ValueError exception

except (IndexError, ZeroDivisionError):
   # handle multiple exceptions
   # IndexError and ZeroDivisionError

except:
   # handle all other exceptions

finally:
   # cleanup resources
#!/usr/bin/env python

# zero_division.py


def input_numbers():

    a = float(input("Enter first number:"))
    b = float(input("Enter second number:"))
    return a, b


x, y = input_numbers()
print(f"{x} / {y} is {x/y}")

In this script, we get two numbers from the console. We divide these two numbers.
If the second number is zero, we get an exception.

Enter first number:3
Enter second number:0
Traceback (most recent call last):
    File "C:/Users/Jano/PycharmProjects/Simple/simple.py", line 14, in <module>
    print(f"{x} / {y} is {x/y}")
ZeroDivisionError: float division by zero
#!/usr/bin/env python

# zero_division2.py


def input_numbers():

    a = float(input("Enter first number:"))
    b = float(input("Enter second number:"))
    return a, b


x, y = input_numbers()

while True:

    if y != 0:

        print(f"{x} / {y} is {x/y}")
        break

    else:

        print("Cannot divide by zero")
        x, y = input_numbers()

First, we simply check that y value is not zero. If the
y value is zero, we print a warning message and repeat the input
cycle again. This way we handled the error and the script is not interrupted.

$ ./zero_division2.py
Enter first number:4
Enter second number:0
Cannot divide by zero
Enter first number:5
Enter second number:0
Cannot divide by zero
Enter first number:5
Enter second number:6
5.0 / 6.0 is 0.8333333333333334
#!/usr/bin/env python

# zerodivision3.py


def input_numbers():

    a = float(input("Enter first number:"))
    b = float(input("Enter second number:"))
    return a, b


x, y = input_numbers()


try:
    print(f"{x} / {y} is {x/y}")

except ZeroDivisionError:

    print("Cannot divide by zero")
    x, y = input_numbers()

We place the code where we expect an exception after try keyword.
The except keyword catches the exception if it is raised.
The exception type is specified after the except keyword.

except ValueError:
    pass
except (IOError, OSError):
    pass
#!/usr/bin/env python

# value_error.py


def read_age():

    age = int(input("Enter your age: "))

    if age < 0 or age > 130:
        raise ValueError("Invalid age")

    return age


try:
    val = read_age()
    print(f"Your age is {val}")

except ValueError as e:
    print(e)

In the example, we have a function that read age as input from
the user. When the user provides incorrect value, we raise
a ValueError exception.

if age < 0 or age > 130:
    raise ValueError("Invalid age")

return age
#!/usr/bin/env python

# multiple_exceptions.py

import os

try:

    os.mkdir('newdir')
    print('directory created')

    raise RuntimeError("Runtime error occurred")

except (FileExistsError, RuntimeError) as e:
    print(e)

The code example catches two exceptions in one except statement:
FileExistsError and RuntimeError.

os.mkdir('newdir')

A new directory is created with the os.mkdir() method. If the directory
already exists, a FileExistsError is triggered.

raise RuntimeError("Runtime error occurred")
#!/usr/bin/env python

# exception_argument.py

try:
    a = (1, 2, 3, 4)
    print(a[5])

except IndexError as e:

    print(e)
    print("Class:", e.__class__)

From the exception object, we can get the error message or the class name.

$ ./exception_as.py
tuple index out of range
Class: <class 'IndexError'>
#!/usr/bin/env python

# interrupt.py

try:
    while True:
       pass

except KeyboardInterrupt:

    print("Program interrupted")

The script starts and endless cycle. If we press Ctrl+C,
we interrupt the cycle. Here, we caught the KeyboardInterrupt
exception.

Exception
  BaseException
    KeyboardInterrupt
#!/usr/bin/env python

# interrupt2.py

try:
    while True:
        pass

except BaseException:

    print("Program interrupted")
#!/usr/bin/env python

# user_defined.py


class BFoundEx(Exception):

    def __init__(self, value):
        self.par = value

    def __str__(self):
        return f"BFoundEx: b character found at position {self.par}"


string = "There are beautiful trees in the forest."

pos = 0

for i in string:

    try:

        if i == 'b':
            raise BFoundEx(pos)
        pos = pos + 1

    except BFoundEx as e:
        print(e)

In our code example, we have created a new exception. The exception is derived
from the base Exception class. If we find any occurrence of
letter b in a string, we raise our exception.

$ ./user_defined.py
'BFoundEx: b character found at position 10'
#!/usr/bin/env python

# cleanup.py

f = None

try:

    f = open('data.txt', 'r')
    contents = f.readlines()

    for line in contents:
        print(line.rstrip())

except IOError:

    print('Error opening file')

finally:

    if f:
        f.close()
#!/usr/bin/env python

# stacktrace_ex.py

import traceback


def myfun():

    def myfun2():

        try:
            3 / 0

        except ZeroDivisionError as e:

            print(e)
            print("Class:", e.__class__)

            for line in traceback.format_stack():
                print(line.strip())

    myfun2()


def test():
    myfun()


test()

In the example, we have a division by zero exception in the nested
myfun2 function.

for line in traceback.format_stack():

The format_stack() extracts the raw traceback from the current
stack frame and formats it into a list of tuples. We traverse the list of tuples
with a for loop.

$ ./stacktrace_ex.py
division by zero
Class: <class 'ZeroDivisionError'>
File "C:/Users/Jano/PycharmProjects/Simple/simple.py", line 30, in <module>
    test()
File "C:/Users/Jano/PycharmProjects/Simple/simple.py", line 27, in test
    myfun()
File "C:/Users/Jano/PycharmProjects/Simple/simple.py", line 23, in myfun
    myfun2()
File "C:/Users/Jano/PycharmProjects/Simple/simple.py", line 20, in myfun2
    for line in traceback.format_stack():

Answer by Justice Norman

Python 2 handles all errors with exceptions.
,An exception is a signal that an error or other unusual condition has occurred. There are a number of built-in exceptions, which indicate conditions like reading past the end of a file, or dividing by zero. You can also define your own exceptions.
,8. Errors and Exceptions in The Python Tutorial, docs.python.org,All built-in Python exceptions

import random
try:
  ri = random.randint(0, 2)
  if ri == 0:
    infinity = 1/0
  elif ri == 1:
    raise ValueError("Message")
    #raise ValueError, "Message" # Deprecated
  elif ri == 2:
    raise ValueError # Without message
except ZeroDivisionError:
  pass
except ValueError as valerr:
# except ValueError, valerr: # Deprecated?
  print valerr
  raise # Raises the exception just caught
except: # Any other exception
  pass
finally: # Optional
  pass # Clean up

class CustomValueError(ValueError): pass # Custom exception
try:
  raise CustomValueError
  raise TypeError
except (ValueError, TypeError): # Value error catches custom, a derived class, as well
  pass                          # A tuple catches multiple exception classes

Answer by Azariah Holland

When zero shows up in the denominator of a division operation, a ZeroDivisionError is raised.,We re-write the given code as follows to handle the exception and find its type.,How to catch IndentationError Exception in python?,How to catch EnvironmentError Exception in Python?

Example

import sys
try:
x = 11/0
print x
except Exception as e:
print sys.exc_type
print e

Output

<type 'exceptions.ZeroDivisionError'>
integer division or modulo by zero


Answer by Jianna Krueger

If an exception has arguments, they are printed as the last part (‘detail’) of
the message for unhandled exceptions.,Even if a statement or expression is syntactically correct, it may cause an
error when an attempt is made to execute it. Errors detected during execution
are called exceptions and are not unconditionally fatal: you will soon learn
how to handle them in Python programs. Most exceptions are not handled by
programs, however, and result in error messages as shown here:,Many standard modules define their own exceptions to report errors that may
occur in functions they define. More information on classes is presented in
chapter Classes.,Most exceptions are defined with names that end in “Error”, similar to the
naming of the standard exceptions.

>>> while True print('Hello world')
  File "<stdin>", line 1
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax

Answer by Kingston Davila

The simplest way to handle exceptions is with a «try-except» block: ,Give example of multiple excepts. Handling multiple excepts in one line. ,In the «general error handling» section above, it says to catch all exceptions, you use the following code: ,Someone pointed out that «except» catches more than just «except Exception as e.»

   1 (x,y) = (5,0)
   2 try:
   3   z = x/y
   4 except ZeroDivisionError:
   5   print "divide by zero"

Answer by Edith Massey

I’m getting the following error while executing a python code:, Python error ZeroDivisionError division by zero ,48258/python-error-zerodivisionerror-division-by-zero,

The error is thrown in this line

matchPercentage …READ MORE

I’m getting the following error while executing a python code:

ZeroDivisionError: division by zero
ZeroDivisionError: division by zero
In [55]:

x = 0
y = 0
z = x/y
---------------------------------------------------------------------------
ZeroDivisionError                         Traceback (most recent call last)
<ipython-input-55-30b5d8268cca> in <module>()
      1 x = 0
      2 y = 0
----> 3 z = x/y

ZeroDivisionError: division by zero

Понравилась статья? Поделить с друзьями:
  • Int object is not iterable python ошибка
  • Indesit wiun 102 сброс ошибок
  • Indesit wiun 102 ошибки расшифровка
  • Indesit wiun 102 ошибка f08
  • Indesit wiun 102 коды ошибок мигает