Arithmetic with Boolean values

Terry Reedy tjreedy at udel.edu
Sat Aug 11 20:25:51 EDT 2012


On 8/11/2012 7:13 PM, Chris Angelico wrote:
> On Sun, Aug 12, 2012 at 8:30 AM, John Ladasky
> <john_ladasky at sbcglobal.net> wrote:
>> In [7]: 1 + not(len(L) % 2)
>> ------------------------------------------------------------
>>     File "<ipython console>", line 1
>>       1 + not(len(L) % 2)
>>             ^
>> SyntaxError: invalid syntax
>
> This appears to be a limitation of the parser; it's trying to
> interpret "not" as a binary operator.

I think not. It is lower precedence than all arithmetic operators. The 
following is worth knowing about and occasionally reviewing.
http://docs.python.org/py3k/reference/expressions.html#summary

() around % is not needed; not len(L) % 2 works same. So parser sees

1 + not len(L) % 2

with + given higher precedence than not, So it parses as (1 + not) and 
croaks, as indicated by caret. (We humans see that that is impossible 
and may boost the precedence in context.)

> 1 + (not(len(L) % 2))

== 1 + (not len(L) % 2)
>
> Works just fine with parentheses to enforce the correct interpretation.
>
> This also works in Python 3.2, fwiw (except that you need
> list(range(5)) to create the sample list).

-- 
Terry Jan Reedy




More information about the Python-list mailing list