[Tutor] operator order
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
> not this:
> >>> d
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:
(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.
Author of the Learn to Program web site
More information about the Tutor