FREE ONLINE INTERACTIVE COURSE

Python 3

FOR BEGINNERS

LESSON 2
PAGE 4 / 4
Arithmetic operators
Home >>> Free online lessons

Precedence and Associativity

It is essential to understand how an expression is evaluated and for this we need certain fundamental notions.

Priority (precedence) of operators. You are already accustomed to this notion, knowing that it indicates the order of operations.

Operators' association. The notion can be new to you and it is of two kinds: from left to right and from right to left. From the beginning we specify that the operators with the same priority have the same associativity.

To understand the notion of associativity, we start from an expression in which operands are linked by operators with the same priority. If the associativity of the operators is from left to right, the first operation performed is the one corresponding to the first operator on the left, the second operation is the one corresponding to the second one on the left, etc. Obviously, if the associativity is from right to left, the first operation to be performed is that of the operator on the right, and so on.

For example, if we have the operation 7 * 2 // 4, we have the associative from left to right, so we perform first 7 * 2, then 14 // 4, the result being obvious, 3. So, here the operators have the same priority.

On the other hand, with the help of the "**" operator, you can raise a number to the power of an exponent. In this case, the associativity is from right to left. For 2 ** 3 ** 2, first 32 is performed, the result being 9. Then 29, which obtains the value of 512.

Note that 2 ** 3 ** 2 is equivalent to 2 ** (3 ** 2).

If we use parentheses, the result differs, of course, because they have a higher priority than the "**" operator:

(2 ** 3) ** 2

The parenthesis is performed first, i.e. 23 = 8, then 82, the final result being 64.

Conclusion

Note that when writing expressions, the result depends on the programming environment used, in this case Python, version 3 , as well as all the syntax rules and properties by which they are evaluated.
Congratulations! The lesson is over!
 home   list  LESSONS   arrow_upward