How do I use try except on multiple elements?

Viewed 53

So I'm trying to set several values divided by other variables that could be 0, so I decided to use try except:

    try:
        p = pacific / float(a)
        m = mountain / float(b)
        c = central / float(c)
        e = eastern / float(d)
    except ZeroDivisionError:
        p = 0
        m = 0
        c = 0
        e = 0

    print(p)
    print(m)
    print(c)
    print(e)

So since a b c and d could all possibly be zero, I wanted to create an instance where if p m c or e ends up being undefined as a result of a b c or d being zero, then I want to set only that one specific undefined variable (p m c or e) to 0. For example, if p m c all divide out into floats, but d is 0 and e becomes undefined, I want to return the number values of p, m, and c, but e as 0. How do I achieve this? My code above, sets p m c and e all to 0 if only a single variable among p m c or e is undefined. I know I could probably brute force this and make a try except for each of the 4 variables, but I'm looking for a way to shorten this piece of code.

3 Answers

You could write a function to try the division and return a default.

def mydiv(a, b):
    try:
        return a/float(b)
    except ZeroDivisionError:
        return 0

p = mydiv(pacific, float(a))
m = mydiv(mountain, float(b))
c = mydiv(central, float(c))
e = mydiv(eastern, float(d))

You will need to check each entry, but you can do so with minimal code

p = pacific  / float(a) if float(a)!=0 else 0
m = mountain / float(b) if float(b)!=0 else 0
c = central  / float(c) if float(c)!=0 else 0
e = eastern  / float(d) if float(d)!=0 else 0

print(p)
print(m)
print(c)
print(e)

You may be better off using numpy arrays, which have nice error handling capabilities and involve much less code. Division by zero produces infinity, which is easily replaced with zero.

import numpy as np
pmce  = np.array([1,2,3,4]) # numerator
abcd = np.array([5,6,0,8]) # denominator

with np.errstate(divide='ignore'):
    pmce_new = pmce/abcd
    pmce_new[np.isinf(pmce_new)] = 0

print(pmce_new)

Output:

[0.2    0.33333333     0.     0.5 ]
Related