Simple operator associativity and precedence rules (was: 2**2**2**2**2 wrong? Bug?)

Ben Finney bignose+hates-spam at benfinney.id.au
Tue Jul 10 04:05:49 EDT 2007


"Jim Langston" <tazmaster at rocketmail.com> writes:

> 2**2 = 4
> 4**2 = 16
> 16**2 = 256
> 256**2 = 65536
> 65536**2 = 4294967296
>
> In fact, if I put (2**2)**2**2**2
> it comes up with the correct answer, 4294967296

I have never gone wrong with mathematical expressions since I reduced
the set of operator associativity and precedence rules to these:

  1. Addition and subtraction have the same precedence, and are
     left-to-right associative

  2. Multiplication and division have the same precedence, and are
     left-to-right associative

  3. Use parentheses to make explicit all other precedence and
     associativity

The specific programming language I use at any given moment might
follow more complex rules, but I ignore them in favour of the above
set. I thus spend less time uselessly thinking about tasks I should be
delegating to explicit expression syntax, and am never surprised by a
misunderstood mathematical associativity or precedence rule.

-- 
 \        "A hundred times every day I remind myself that [...] I must |
  `\       exert myself in order to give in the same measure as I have |
_o__)             received and am still receiving"  -- Albert Einstein |
Ben Finney



More information about the Python-list mailing list