In some academic books I found that python, for its arithmetic operators, has specific priorities and associativities that guide the order of execution of operations.
Here are the related values for the basic arithmetic operators (table found in a python book and consistent with other websites, such as https://www.programiz.com/python-programming/precedence-associativity ):
However, when I perform some expressions in python, I get a result that is not consistent with that hierarchy and associativity of operations:
I give examples:
>>>-13//-2
6
Which is consistent (first the sign change of both terms (-13) and (-2) is performed and then the integer division.
>>>1-13//-2
8
Which is also consistent. Following the reasoning given in the table, first the sign of 2 → (-2) would be changed, then the integer division is performed, which gives -7, since -7 is the value less than -6.5, which would give the result of the division normal; Finally, the subtraction 1-(-7) = 8 should be performed and from there the result.
However, when performing:
>>>13//-2%2
1
This result does not seem to obey the left associativity of the integer division and modulo operators belonging to the same precedence (hierarchy). I also can't get to the same result by following precedence and associativity. Since the sign change 2→(-2) should be done first, then the integer division should be associated from the left, giving (-7) and finally the modulo operation whose result should be -1 should be done.
Is there anything you're not taking into account? Is my way of using precedence and associativity values wrong? Or is it due to some consideration about python that I am unaware of.
Thanks in advance.