1 or 1/0 doesn't raise an exception

Benjamin Kaplan benjamin.kaplan at case.edu
Sun Dec 14 18:09:33 CET 2008


On Sun, Dec 14, 2008 at 2:38 AM, Gabriel Genellina
<gagsl-py2 at yahoo.com.ar>wrote:

> En Sun, 14 Dec 2008 02:40:10 -0200, Benjamin Kaplan
> <benjamin.kaplan at case.edu> escribió:
>
>  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?
>>> >
>>> > http://en.wikipedia.org/wiki/Short-circuit_evaluation
>>>
>>> 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.
>>>
>>
>> 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).
>>
>
> No: &, | (and ^, too) perform bitwise operations in Python, C and Java:
>

Perhaps I should have mentioned that you have to restrict yourself to bools
(or 0 and 1) when doing this. I know that they perform bitwise operations
when you do them with ints- I was assuming the OP was dealing with bools.

>
> py> 1 & 2
> 0
>
> && and || --in both C and Java-- are like `and` and `or` in Python; they
> perform logical operations, and short-circuit evaluation of their operands.
> If you want to evaluate a logical expression without short circuiting, do
> that explicitely:
>
> a = first part
> b = second part
> if a or b: ...
>

> --
> Gabriel Genellina
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20081214/a2bacf0b/attachment.html>


More information about the Python-list mailing list