tags:

views:

407

answers:

3

I "accidentally" came across 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

+25  A: 

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.

dash-tom-bang
+4  A: 

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.

Spidey
+4  A: 

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.

UncleZeiv
I like the last. ++i is valid, it just doesn't do what it does in other languages :)
extraneon
Exactly! (and a bit scary)
UncleZeiv