1 or 1/0 doesn't raise an exception

Daniel Fetchinson fetchinson at googlemail.com
Sun Dec 14 04:49:36 CET 2008

>> Is it a feature that
>> 1 or 1/0
>> returns 1 and doesn't raise a ZeroDivisionError? If so, what's the
>> rationale?
> Yes, it's a feature:
> http://en.wikipedia.org/wiki/Short-circuit_evaluation
> When you have "True or False", you know it's true by the time
> you've got the first piece, so there's no need to evaluate the
> 2nd piece.  The opposite is helpful too:
>    lst = [some list or an empty list]
>    ...
>    if lst and lst[0] == 42:
> This ensures that the "lst[0]" doesn't fail if lst is empty,
> because lst evaluating to false (an empty list) short-circuits
> preventing the evaluation of "lst[0]".

Okay, it's clear, thanks.

Let me just point out that unsuspecting people (like me) might rely on
the whole expression to be evaluated and rely on exceptions being
raised if needed.

So from now on I will not do!

Psss, psss, put it down! - http://www.cafepress.com/putitdown

More information about the Python-list mailing list