4

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?

3
  • 2
    If you subtract minus two from something, that's the same thing as adding two to it. Commented Jun 11, 2017 at 12:24
  • Related (but probably not a duplicate): stackoverflow.com/q/1485841/5827958 Commented Jun 11, 2017 at 12:33
  • 1
    @zondo: no, that's very much a suitable dupe target, the explanation is exactly the same. Commented Jun 11, 2017 at 12:40

2 Answers 2

5

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)))))) 
Sign up to request clarification or add additional context in comments.

Comments

4
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.