Sunday, May 24, 2020

Binding of the operators


The binding of the operator determines the order of computations performed by some operators with equal priority, put side by side in one expression.

In Python, most of the operators have left-sided binding. That means the calculation of the expression is conducted from left to right.





In correct way, from left to right:

9 % 6 gives 3 and then 3 % 2 gives 1
In incorrect way, from right to left:
6 % 2 gives 0 and then 9 % 0 causes a fatal error.

In Python, modulo operator has left-sided binding.







In correct way, from right to left:

2 ** 3 gives 8 and then 2 ** 8 gives 256
In incorrect way, from left to right:
2 ** 2 gives 4 and then 4 ** 3 gives 64

In Python, exponentiation operator has right-sided binding.


Operator Priorities


Example:






Parentheses with operators


According to the arithmetic rules, sub-expressions in parentheses are always calculated first.


No comments:

Post a Comment