EMZETT.
Login

ZeroDivisionError and ValueError (Python)

In short: A division by zero raises ZeroDivisionError; a ValueError occurs when a value has the right type but an unsuitable content.

In more detail: Both errors stand for input data that the code cannot process. They are common especially with user input, files and calculations.

In Depth

ZeroDivisionError

print(10 / 0)   # ZeroDivisionError: division by zero

10 % 0 and 10 // 0 raise it too. Solution: check before dividing (if denominator != 0:) and handle the case (default value, error message). With floating-point numbers a result can be “almost zero”; then work with a tolerance (math.isclose).

ValueError

int("abc")        # ValueError: invalid literal for int() with base 10: 'abc'
float("1,5")      # ValueError (comma instead of dot)
import math
math.sqrt(-1)     # ValueError: math domain error
a, b = [1, 2, 3]  # ValueError: too many values to unpack

Solutions: check or clean inputs (text.strip(), replace comma with dot), secure with str.isdigit() or try/except ValueError and give the user an understandable message. When unpacking, check the list length.

Catching errors

try:
    number = int(input("Number: "))
    print(100 / number)
except ValueError:
    print("Please enter a whole number.")
except ZeroDivisionError:
    print("You cannot divide by zero.")

Catch only specific errors, not a blanket except:; otherwise you hide real programming errors. Validate inputs early and give clear feedback.

See also: TypeError, KeyError and IndexError, Exit code 1