How does the following expression work in python?
Check out the Python data model and operator precedence. You find the magic methods __neg__
, __pos__
, __abs__
, and __invert__
all take a single argument. Other than __abs__
, these are implemented as operators, -
for __neg__
, +
for __pos__
, and ~
for __invert__
. Looking at operator precedence, these bind more tightly than any binary arithmetic operators. __pos__
just returns the int unchanged, whereas __neg__
returns the same int but with its sign changed. So the interpreter is just repeatedly applying that operation over and over until it finally finds a left operand and actually does some arithmetic.
It's amazing that you are playing with python. At first I was also astonished. But thinking it deeply, It's just simple math! It doesn't matter how many plus you are giving in front of a number. It stays the same.
++++++++++++++(1) = 1
But it matters if there is any minus.
+++++++++-(1) = -1
(parenthesis is just for clearness) So in your code at the first one the value doesn't change because there is just plus. But in the second one the value of 1 changes to -1 because there is a minus. So the result is zero. But if there was two minus, the result would be 2. Because -- = +.
>>> 1 +++++++++++++-- 1
2
There are no post / pre increment / decrement operators
in python.
We can see ++
or --
as multiple signs getting multiplied, like we do in maths. (-1) * (-1) = (+1).
So the first expression will evaluate to (1)+ (+1)= 2
the other one, (+1) + -(+1)=(+1)-(+1)=1-1=0
For more see here.
You have to use the logic of brackets and arithmetic operations for this kind of calculation.
1--2 becomes,
1-(-(2)) = 1-(-2)
= 1+2
= 3
1+++1 becomes,
1+(+(+1)) = 2
1++-1 becomes,
1+(+(-1)) = 0