Python is one of the most simple and powerful programming languages in the world. The insane number of libraries both third-party and in-house allows programmers to infuse a lot of functionality in their code natively.
That said, general programming errors still pop up from time to time. In this article, we’re talking about a Math range error in Python.
What causes this error?
Python uses operands for mathematical operations that have declared data types having their own specific maximum limits. When a variable exceeds that limit, you’ll end up running into this limit overflow error.
Also read: How to solve the Tower of Hanoi problem using Python?
How to fix this?
Here are two fixes you can try out.
Check your inputs
The easiest thing you can do to avoid this error is put in a simple if condition to check the value of the input for any overflow errors before you use the value for mathematical operations. You’re essentially using a condition to calculate the value of the exponent before it can trigger an error in the code.
import math
val = 1000
if val<50:
answer=math.exp(val)
print(answer)
else:
print("Input value is greater than allowed limit")
This way you can raise an error to the user before the program runs into any problems and throws a runtime error halting the entire script.
Use a try-except block
This solution is the same in principle as the previous one but instead of using an if conditional statement, you use a try-except block instead to catch the error before it happens and use it to either trigger a different block in your code or ask the user for another input.
try:
ans = math.exp(200000)
except OverflowError:
ans = float('inf')
It’s just a slightly more elegant solution where the exception is handled properly and a separate code block is triggered based on whether or not the value overflows the specified data type.
Also read: Fix: Python was not found; run without arguments to install