1 or 1/0 doesn't raise an exception

Benjamin Kaplan benjamin.kaplan at case.edu
Sun Dec 14 05:40:10 CET 2008


On Sat, Dec 13, 2008 at 10:49 PM, Daniel Fetchinson <
fetchinson at googlemail.com> wrote:

> >> 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!



If you want both expressions evaluated, you can use & and |, just like in C
and Java (&& and || are used for short circuit evaluation in those
languages).
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20081213/27575d9f/attachment.html>


More information about the Python-list mailing list