Arithmetic errors in Python are common and occur when mathematical operations fail to execute properly. These errors can be caused by various issues, such as invalid input, division by zero, or exceeding number limits. Understanding the causes and how to handle these errors is important for writing robust Python programs.
Python
a = 10
b = 0
res = a / b # Raises ZeroDivisionError
Output
Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 3, in <module>
res = a / b # Raises ZeroDivisionError
~~^~~
ZeroDivisionError: division by zero
In this article, we'll explore common types of arithmetic errors, their causes and how to handle them.
Types of Airthmetic Errors in Python
OverflowError
An OverflowError occurs when a number exceeds the maximum limit that Python's data types can represent, typically in cases of large numbers, recursion or exponentiation. For Example:
Python
a = 10 ** 10000 # Results in OverflowError in some systems
print(a)
Output
Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 2, in <module>
print(a)
~~~~~^^^
ValueError: Exceeds the limit (4300 digits) for integer string conversion; use sys.set_int_max_str_digits() to increase the limit
To handle an OverflowError, break calculations into smaller parts or use data types like Python's decimal module for high-precision arithmetic.
Python
from decimal import Decimal
a = Decimal(10) ** 10000 # Handling large numbers using Decimal
print(a)
Output1.000000000000000000000000000E+10000
ValueError
ValueError occurs when an invalid operation is performed on incompatible data types, such as adding a string to an integer.
Python
a = "10"
b = 5
res = a + b # Raises ValueError because num1 is a string
Output
Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 3, in <module>
res = a + b # Raises ValueError because num1 is a string
~~^~~
TypeError: can only concatenate str (not "int") to str
To handle a ValueError, ensure values are of the correct data type before performing operations, and use exception handling to catch and manage errors gracefully.
Python
a = "10"
b = 5
try:
res = int(a) + b # Convert num1 to an integer before addition
print(res)
except ValueError:
print("Invalid input")
TypeError
TypeError occurs when performing arithmetic operations on incompatible data types, such as adding a list and a number.
Python
a = [1, 2, 3]
b = 4
res = a + b # Raises TypeError because a list and integer can't be added
Output
Hangup (SIGHUP)
Traceback (most recent call last):
File "/home/guest/sandbox/Solution.py", line 3, in <module>
res = a + b # Raises TypeError because a list and integer can't be added
~~^~~
TypeError: can only concatenate list (not "int") to list
To handle a TypeError, ensure operands are of the correct type before operations, and use type checking or try-except blocks to manage errors.
Python
a = [1, 2, 3]
b = 4
if isinstance(a, int) and isinstance(b, int):
result = a + b
else:
print("Both operands must be integers.")
OutputBoth operands must be integers.
FloatingPoint Error
FloatingPointError occurs when floating-point arithmetic results in precision issues leading to unexpected outcomes, especially in operations like comparisons.
Python
a = 0.1 + 0.2
b = 0.3
print(a == b) # False due to floating-point precision error
To handle a FloatingPointError, use the math.isclose() function to check for approximate equality of floating-point numbers.
Python
a = 0.1 + 0.2
b = 0.3
import math
if math.isclose(a, b):
print("The numbers are approximately equal.")
else:
print("The numbers are not equal.")
OutputThe numbers are approximately equal.
Similar Reads
Python: AttributeError In every programming language, if we develop new programs, there is a high chance of getting errors or exceptions. These errors yield to the program not being executed. One of the error in Python mostly occurs is "AttributeError". AttributeError can be defined as an error that is raised when an attr
3 min read
Learn Python Basics âPython is a versatile, high-level programming language known for its readability and simplicity. Whether you're a beginner or an experienced developer, Python offers a wide range of functionalities that make it a popular choice in various domains such as web development, data science, artificial in
9 min read
Python Introduction Python was created by Guido van Rossum in 1991 and further developed by the Python Software Foundation. It was designed with focus on code readability and its syntax allows us to express concepts in fewer lines of code.Key Features of PythonPythonâs simple and readable syntax makes it beginner-frien
3 min read
Python - Catch All Exceptions In this article, we will discuss how to catch all exceptions in Python using try, except statements with the help of proper examples. But before let's see different types of errors in Python. There are generally two types of errors in Python i.e. Syntax error and Exceptions. Let's see the difference
3 min read
Indentation in Python In Python, indentation is used to define blocks of code. It tells the Python interpreter that a group of statements belongs to a specific block. All statements with the same level of indentation are considered part of the same block. Indentation is achieved using whitespace (spaces or tabs) at the b
2 min read
Python Print Exception In Python, exceptions are errors that occur at runtime and can crash your program if not handled. While catching exceptions is important, printing them helps us understand what went wrong and where. In this article, we'll focus on different ways to print exceptions.Using as keywordas keyword lets us
3 min read