1 or 1/0 doesn't raise an exception

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sun Dec 14 02:38:05 EST 2008


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:

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




More information about the Python-list mailing list