Error guide · ValueError
ValueError: math domain error
You gave a maths function a value it cannot work with.
Example
import math print(math.sqrt(-4))
What Python says
ValueError: math domain error
As printed by Python 3.12. Other versions may word it slightly differently.
Why it happens
Some maths functions accept only certain values. The square root needs a number that is zero or more, and math.log needs a number above zero. Outside that range the answer is not a real number, so Python stops with a domain error.
How to fix it
import math x = -4 if x >= 0: print(math.sqrt(x)) else: print("No real square root")
Output: No real square root
Tips
- Check the value with an
ifbefore calling the function. math.log(0)andmath.log(-1)raise the same error.- For square roots of negative numbers, Python has a separate
cmathmodule that works with complex numbers.