# Operator precedence problem

Peter Otten __peter__ at web.de
Mon Jun 6 12:38:31 EDT 2016

```Marko Rauhamaa wrote:

> Random832 <random832 at fastmail.com>:
>
>> Sure, it's obvious to _me_ that << and >> have higher precedence than &
>> and |, and that "and" has a higher precedence than "or", but can I
>> assume the other people know this?
>
> No need to assume. Just read the spec:
>
>    lambda         Lambda expression
>    if – else      Conditional expression
>    or             Boolean OR
>    and            Boolean AND
>    not x          Boolean NOT
>    in, not in, is, is not, <, <=, >, >=, !=, ==
>                   Comparisons, including membership tests and identity
>                   tests
>    |              Bitwise OR
>    ^              Bitwise XOR
>    &              Bitwise AND
>    <<, >>         Shifts
>    +, -           Addition and subtraction
>    *, @, /, //, % Multiplication, matrix multiplication division,
>                   remainder [5]
>    +x, -x, ~x     Positive, negative, bitwise NOT
>    **             Exponentiation [6]
>    await x        Await expression
>    x[index], x[index:index], x(arguments...), x.attribute
>                   Subscription, slicing, call, attribute reference
>    (expressions...), [expressions...], {key: value...}, {expressions...}
>                   Binding or tuple display, list display, dictionary
>                   display, set display
>
>    <URL: https://docs.python.org/3/reference/expressions.html#operat
>    or-precedence>
>
>> [To keep this on-topic, let's assume that this discussion has a goal of
>> getting something along the lines of "always/sometimes/never use
>> "unnecessary" parentheses" into PEP7/PEP8. Speaking of, did you know
>> that C has lower precedence for the bitwise operators &^| than for
>> comparisons? That was something that tripped me up for a very long time
>> and undermined my confidence as to other aspects of the bitwise
>> operators]
>
> Yes, I happened to know that. Python's the same way.

It's not. From the page you linked to:

"""
Unlike C, all comparison operations in Python have the same priority, which
is lower than that of any arithmetic, shifting or bitwise operation.
"""

> However, no need to memorize. It's all there in the spec. Same as with
> stdlib functions. Keep checking the spec.

Nah, I usually try it in the interactive interpreter:

\$ python3 -c 'print(1 < 3 & 2)'
True

\$ echo 'main() { printf("%d\n", 1 < 3 & 2); }' | tcc -run -
0