Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the following expression work in python? [duplicate]

Tags:

python

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.

like image 785
Abdul Niyas P M Avatar asked Jan 01 '21 04:01

Abdul Niyas P M


3 Answers

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
like image 75
Ramesh KC Avatar answered Sep 20 '22 19:09

Ramesh KC


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.

like image 26
a121 Avatar answered Sep 22 '22 19:09

a121


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
like image 32
Zubayer Avatar answered Sep 20 '22 19:09

Zubayer