Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use try except on multiple elements?

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.

like image 254
dl784 Avatar asked Feb 02 '26 10:02

dl784


1 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))
like image 119
tdelaney Avatar answered Feb 03 '26 23:02

tdelaney