How does the following expression work in python?
>>> 1 ++++++++++++++++++++ 1
2
>>> 1 ++++++++++++++++++++-+ 1
0
I thought this would raise SyntaxError
but that was not the case.
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
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With