Operator precedence problem

Uri Even-Chen uri at speedy.net
Sun Jun 5 12:05:16 EDT 2016


My suggestion: Never write expressions, such as  2 ** 3 ** 2 or even 2 * 4
+ 5, without parentheses. Always add parentheses - 2 ** (3 ** 2) (or (2 **
3) **2) or (2 * 4) + 5 (or 2 * (4 + 5)).


*Uri Even-Chen*
[image: photo] Phone: +972-54-3995700
Email: uri at speedy.net
Website: http://www.speedysoftware.com/uri/en/
<http://www.facebook.com/urievenchen>  <http://plus.google.com/+urievenchen>
  <http://www.linkedin.com/in/urievenchen>  <http://twitter.com/urievenchen>

On Sun, Jun 5, 2016 at 6:05 PM, ICT Ezy <ictezy at gmail.com> wrote:

> 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
> --
> https://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list