Operator precedence problem
ICT Ezy
ictezy at gmail.com
Sun Jun 5 11:05:51 EDT 2016
On Sunday, June 5, 2016 at 1:06:21 PM UTC+5:30, Peter Otten wrote:
> ICT Ezy wrote:
>
> >>>> 2 ** 3 ** 2
> > Answer is 512
> > Why not 64?
> > Order is right-left or left-right?
>
> ** is a special case:
>
> """
> The power operator ** binds less tightly than an arithmetic or bitwise unary
> operator on its right, that is, 2**-1 is 0.5.
> """
> https://docs.python.org/3.5/reference/expressions.html#id21
>
> Here's a little demo:
>
> $ cat arithdemo.py
> class A:
> def __init__(self, value):
> self.value = str(value)
> def __add__(self, other):
> return self._op(other, "+")
> def __pow__(self, other):
> return self._op(other, "**")
> def __repr__(self):
> return self.value
> def _op(self, other, op):
> return A("({} {} {})".format(self.value, op, other.value))
> $ python3 -i arithdemo.py
> >>> A(1) + A(2) + A(3)
> ((1 + 2) + 3)
> >>> A(1) ** A(2) ** A(3)
> (1 ** (2 ** 3))
Thank you very much for your explanation
More information about the Python-list
mailing list