1 or 1/0 doesn't raise an exception
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 == 42:
> > This ensures that the "lst" doesn't fail if lst is empty,
> > because lst evaluating to false (an empty list) short-circuits
> > preventing the evaluation of "lst".
> 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
-------------- next part --------------
An HTML attachment was scrubbed...
More information about the Python-list