But if I try to take
5 / 0, I get a division by zero error. And if you have a division calculation in your program where the denominator could be a variable, you might want to take steps to prevent the program from crashing.
And if I try to divide
0, the program doesn’t crash. The function doesn’t do anything. How can we communicate that division by zero has occurred and allow other code to be written around that?
Well, one solution would be to take advantage not just of the
or operator, but of short-circuit evaluation, where I’ll check to see if
0 and if it evaluates to
True, I won’t attempt to do the division.
0, this evaluates to
False and I do the second part of the
or operation, which is to do the division. And I know when I get here that
b will not be
0, because if it was, we would have returned from this operation by this being
True. So again, a subtle difference. I’m going to define a new
On the other hand, if I do attempt division by zero, it returns
True. Importantly, it doesn’t crash, and also I get a value back that I can then use to determine if I had a valid division calculation done or not.
So now that we’ve defined this
divide() function, let’s see how it might be used. I have here a few code snippets. So first, we have our
divide() function, which will return
True if we’re trying to divide by zero. And if we’re not, it will actually return the quotient of
a divided by
And here’s a function where we might use that, called
dividing() for lack of a better term. We prompt the user for values for
a and for
b and then we call the
divide() function, but being sure to save the result to a variable before we try to use that.
We know that if this method returns
True, we tried to do division by zero, so the program should act accordingly. In this case, we’re just going to print
"no result, division by zero attempted".
dividing(). It asks for the first number, say
9. It asks for the second number, divide
2, and we get
4.5. If I call
dividing() again and this time we try to divide by zero, we get that warning.
Become a Member to join the conversation.