[Tutor] a puzzle about -3**2 vs (-3)**2

Alan Gauld alan.gauld at btinternet.com
Fri Jul 31 11:18:14 CEST 2015


On 31/07/15 01:58, D Wyatt wrote:
> I just read in a book a little while ago that ** trumps a negative
> sign?  I am struggling with the audacity of that as -1 is negative 1,
> NOT minus 1.  How can an arithmetic operation trump an attribute of a
> negative integer?

Because Python is a programming language with its own rules
created by its designer. It doesn't need to follow the rules
of math as you understand them.

The decision may have been made because it made parsing
constructs like this easier:

5-2

Is that 2 adjacent numbers 5 and -2? or is it an infix subtraction?
Its easy for us to decide but harder for a computer reading the text.
As the expressions get more complex there are more and more potentially 
ambiguous combinations so the language designer may decide to make the 
language more consistent by defining a set of precedence rules. In
this case that ** is higher than -.

He is quite within his rights to do that. It's his language after all.
Some languages solve these problems by not permitting infix notation,
so in Lisp for example

(3 - 5)

is illegal, you need to do

(- 3 5)

It looks odd to us but that's not the point, its how the language works.
You learn to get used to it. Most languages have some idiosyncrasies 
like this.

HTH

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list