Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using two addition operators for adding two integers valid in python? [duplicate]

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?

like image 473
Praveen kumar Avatar asked Jan 04 '23 21:01

Praveen kumar


2 Answers

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 classes 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))))))
like image 55
Willem Van Onsem Avatar answered Jan 16 '23 20:01

Willem Van Onsem


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.

like image 44
Jörg W Mittag Avatar answered Jan 16 '23 22:01

Jörg W Mittag