I raise an issue in Python 3 where every operation you performed can throw an exception, something like this:
num = 12
a_num = 0
b_num = 1
c_num = 0
try:
a = num/a_num
except Exception as ex:
a = 0
try:
b = num/b_num
except Exception as ex:
b = 0
try:
c = num/c_num
except Exception as ex:
c = 0
print(a)
print(b)
print(c)
This way I get the correct result, but could I just do a try except and get the same result? Since within the same try except if the error occurs, the following calculations will not be performed.
A simple alternative is to ask if the divisor is nonzero before doing the division. This avoids exception generation and is shorter to write.
Here we should use the ternary operator
The result of this expression is
a
if itb
is true, orc
, if it is not.a, b, c
are valid Python expressions.With this we can check the divisor and calculate the value in a single line:
produces:
Expanding a bit on what I mentioned in the comment, the way to not repeat code is usually to extract it into a function, and call it in a loop if possible. In this case:
Now the main program would be simply:
Or, in loop form (rather, generating expression):