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.
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))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With