Guarding arithmetic

Chris Angelico rosuav at gmail.com
Thu Aug 23 05:16:08 EDT 2012


On Thu, Aug 23, 2012 at 7:05 PM, Mark Carter <alt.mcarter at gmail.com> wrote:
> Suppose I want to define a function "safe", which returns the argument passed if there is no error, and 42 if there is one. So the setup is something like:
>
> def safe(x):
>    # WHAT WOULD DEFINE HERE?
>
> print safe(666) # prints 666
> print safe(1/0) # prints 42
>
> I don't see how such a function could be defined. Is it possible?

That can work ONLY if the division of 1/0 doesn't raise an exception.
This is why the concept of NaN exists; I'm not sure if there's a way
to tell Python to return NaN instead of bombing, but it's most likely
only possible with floating point, not integer.

However, there's an easier way.

try:
    print 1/0
except ZeroDivisionError:
    print 42

Catch the exception and do with it what you will.

ChrisA



More information about the Python-list mailing list