I've just started learning python. I was just trying to play with print function. I ended up writing the below code.
print(2 ++ 2)
I expected the Python interpreter to throw an error since I put two addition operators next to each other without putting an integer between them. Contrarily, the python interpreter did not throw any error and returned 4 as output. I also tried the below code:-
print(4 -- 2)
The output was 6.
Could someone explain me these?
2 ++ 2
is interpreted as:
2 ++ 2 == 2 + (+2)
So you perform an addition between 2
and +2
where the second +
is thus an unary plus. The same happens if you write 2 +++ 2
:
2 +++ 2 == 2 + (+(+2))
For the 4 -- 2
case something similar happens:
4 -- 2 == 4 - (-2)
So you subtract -2
from 4
resulting in 6
.
Using two, three (or even more) additions is not prohibited, but for integers/floats it only results in more confusion, so you better do not do this.
There are class
es that define their own unary plus and unary minus operator (like Counter
for instance). In that case ++
can have a different behaviour than +
. So you better do not use ++
(and if you do, put a space between the two +
ses to make it explicit that the second +
is a different operator).
Since there are unary plus and minus operators, anything after the first +
or -
is interpreted as unary. So 2 ++--++- 2
will result in 0
since:
2 ++--++- 2 == 2 + (+(-(-(+(+(-2))))))
2 ++ 2
is
2 + (+2)
and
4 -- 2
is
4 - (-2)
It's just a question of operator precedence, fixity, and arity:
2 ==+-+-+ 2
#>>> True
Note that for numbers, unary prefix +
is defined as the identity function, and unary prefix -
is defined as negation (which means that a double unary prefix --
is the identity function); but Python supports operator overloading, so there is no guarantee that this is true for all objects.
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