Operators and their priorities
So far, we've treated each operator as if it had no connection with the others. Obviously, sich an ideal and simple situation is a rarity in real programming.
Also, you will very often find more than one operator in one expression, and then this presumption is no longer so obvious.
Consider the following expression:
2+3*5
You probably remember from school that Multiplications preed additions.
You surely remember that you should first multiply 3 by 5 and, keeping the 15 in your memory, then add it to 2, thus getting the result of 17.
The phenomenon that causes some operators to act before others is known as the hierarchy of priorities.
Python precisely defines the priorities of all operators, and assumes that operators of a larger (higher) priority perform their operations before the operators of a lower priority.
So, if you know that * has a higher priority that +, the computation of the final result should be obvious.
Operators and their bindings
The binding of the operator determines the order of computations performed by some operators with equal priority, put side by side in one expression.
Most of Python's operators have left-sided binding, which means that the calculation of the expression is conducted from left to right.
This simple example will show you how it works. Take a look:
print(9 % 6 % 2)
There are two possible ways of evaluating this expression:
Run the example and see what you get.
The result should be 1. This operator has left-sided binding. But there's one interesting exception.
Operators and their bindings: exponentiation
Repeat the experiment, but now with exponentiation.
Use this snippet of code:
print(2 ** 2 ** 3)
The two possible results are:
run the code. What do you see?
The result clearly shows that the exponentiation operator uses right-sided binding.