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.
In simple term in any arithmetic operation when value divided by zero then in Python throw ZeroDivisionError.
You can see complete Python exception hierarchy through this link : Python: Built-in Exceptions Hierarchy.
In the Python program will throw ZeroDivisionError in case of num_list is not having any element then it’s length become 0 and while executing this program will through ZeroDivisionError.
num_list= total=0 avg=total/len(num_list) print("Average:"+avg)
ZeroDivisionError : Division by Zero
While implementing any program logic and there is division operation make sure always handle ArithmeticError or ZeroDivisionError so that program will not terminate. To solve above problem follow this example:
num_list= total=0 try: avg=total/len(num_list) print("Average:"+avg) except ZeroDivisionError: print ("Zero Division Error occurred")
Zero Division Error occurred.
In this above modified code applied exception handling for particular code section so that program will not terminate.
Learn Python exception handling in more detain in topic Python: Exception Handling
Let me know your thought on it.
Happy Learning !!!
One thought on “[Solved] Python ZeroDivisionError: division by zero in Python”