Reputation: 150624
Today I have started to learn Python. The first things I learned were values, expressions and (arithmetic) operators. So far, everything makes sense, except one thing that I don not get:
While
2+2
evaluates to 4
(which makes sense),
2+
results in a SyntaxError
(which also makes sense). But what – from my point of view – does not make sense is the following line of code:
2+++2
This results in 4
as well, and I wonder why. If I can compare this to JavaScript (which I use on a day-to-day basis), this results in an error in JavaScript.
So, two questions:
+
signs?Upvotes: 6
Views: 75
Reputation: 926
According to the official documentation here,
+2 # refers to 2
2+++2# unary + has higher precedence than addition
2++2 # same logic
2+2
4
Upvotes: 3
Reputation: 311188
Python has an unary +
operator - +2
will evaluate to 2
. So, that expression is actually evaluated as:
2+(+(+2))
Which, of course, is 4
.
Upvotes: 10