I was just playing around with the python command line and the ** operator, which as far as I know performs a power function. So 2 ** 3 should be (and is) 8 because 2 * 2 * 2 = 8.
Can someone explain the behavior I found? I don't see any way to group the operations with parentheses to actually get a result of 65536 like was attained here.
>>> 2 ** 2 ** 2
16
>>> 2 ** 2 ** 2 ** 2
65536
>>> (2 ** 2 ** 2) ** 2
256
Right-associative operators of the same precedence are evaluated in order from right to left. For example, assignment is right-associative.
Associativity can be either Left to Right or Right to Left. For example: '*' and '/' have same precedence and their associativity is Left to Right, so the expression “100 / 10 * 10” is treated as “(100 / 10) * 10”.
Python Operator Associativity Here the multiplication * and division / operators have left to right associativity.
Multiplication and both division operators have the same precedence, which is higher than addition and subtraction, which also have the same precedence.
Explanation: Option 1: Unary Operators have associativity right to left in C++.
Operator Associativity We use associativity when two or more than two operators with the same precedence are present in the same expression. Example, The precedence of Division and Multiplication arithmetic operators is the same.
2** (2**(2**2))
from http://docs.python.org/reference/expressions.html
Operators in the same box group left to right (except for comparisons, including tests, which all have the same precedence and chain from left to right — see section Comparisons — and exponentiation, which groups from right to left).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With