Why is i++++++++i valid in python?
I "accidentally" came ac开发者_如何学运维ross this weird but valid syntax
i=3
print i+++i #outputs 6
print i+++++i #outputs 6
print i+-+i #outputs 0
print i+--+i #outputs 6
(for every even no: of minus symbol, it outputs 6 else 0, why?)
Does this do anything useful?
Update (Don't take it the wrong way..I love python): One of Python's principle says There should be one-- and preferably only one --obvious way to do it. It seems there are infinite ways to do i+1
Since Python doesn't have C-style ++ or -- operators, one is left to assume that you're negating or positivating(?) the value on the left.
E.g. what would you expect i + +5
to be?
i=3
print i + +(+i) #outputs 6
print i + +(+(+(+i))) #outputs 6
print i + -(+i) #outputs 0
print i + -(-(+i)) #outputs 6
Notably, from the Python Grammar Specification, you'll see the line:
factor: ('+'|'-'|'~') factor | power
Which means that a factor in an expression can be a factor preceded by +
, -
, or ~
. I.e. it's recursive, so if 5
is a factor (which it is because factor->power->NUMBER), then -5
is a factor and so are --5
and --------5
.
The plus signs are considered unary operators to the right most i
variable, as in +(-3) = -3, or +(+(+3))) = 3. Just the left most sign (plus or minus) are parsed as binary, so i+++i = i + (+(+i)), which translates to i + i = 3 + 3 = 6, in your example.
The other expressions follow the same principle.
That should read
print i + (+ (+i) )
that is, the first sign is the addition operator, the other ones are infix signs
+i
and (unfortunately)
++i
are thus valid statements.
精彩评论