[Tutor] operator order
Alan Gauld
alan.gauld at btinternet.com
Fri Feb 1 01:11:14 CET 2013
On 31/01/13 18:36, heathen wrote:
> why is this:
>
> >>> d = 2
> >>> d *= 3 + 4
> >>> d
> 14
>
> not this:
> >>> d
> 10
Others have answered but I'll add my two cents variation...
d *= 3+4 works like
d *= X -> d = d * X
so what is X? Is it the 3 or the 3+4.
Let's put some parentheses around things to make it unambiguous:
where X=(3+4)
(d = d * (3+4)) -> 14 that all works OK
where X = 3
((d = d * 3) + 4)
which is a syntax error since assignment doesn't return
a value in Python...
So it has to be X = (3+4) to make any kind of sense.
In these cases you have to think the way the computer thinks.
How is Python going to interpret it? In the second case it can't.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list