Operators and their priorities
So far, we've treated each operator as if it had no connection with the others. Obviously, such 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 precede 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 than +, the computation of the final result should be obvious.
No comments:
Post a Comment