ZeroDivisionError: division by zero solution based on try-except module

As the name suggests, ZeroDivisionError: division by zero is the case where the divisor is 0, which can also be understood as the case where the denominator is 0. Such as 1/0, 2/0, 3/0, etc., but in some fields we may need a 0 value at the denominator position. For example, I want to compare the size of the numerator and the denominator, and obtain the relatively small value as a variable, including 0.

For the above situation, you can use the try-except exception capture module to handle it. Here, when the divisor (denominator) is set to 0, the exception is captured, and then 0 is directly assigned to the new variable:

Simple example, without using try-except module:

A=[1,2,3]
for B in A:
    C = B/max(B-2,0)
    print(C)

Output error: ZeroDivisionError: division by zero

Using the try-except module:

A=[1,2,3]
for B in A:
    try:
        C = B/max(B-2,0)
        print(C)
    except ZeroDivisionError:
        C =0
        print(C)
            

Normal output: 0 0 3.0

This method can be used to define it according to the specific situation. 

Guess you like

Origin blog.csdn.net/qq_38563206/article/details/134187348