1 or 1/0 doesn't raise an exception

Tim Chase python.list at tim.thechases.com
Sat Dec 13 21:23:53 EST 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]".

-tkc





More information about the Python-list mailing list