How does Python evaluate the expression 1+++2
?
How many ever +
I put in between, it is printing 3
as the answer. Please can anyone explain this behavior
And for 1--2
it is printing 3
and for 1---2
it is printing -1
For those of you who are unfamiliar with this series, which has come to be known as the Ramanujan Summation after a famous Indian mathematician named Srinivasa Ramanujan, it states that if you add all the natural numbers, that is 1, 2, 3, 4, and so on, all the way to infinity, you will find that it is equal to -1/12.
only equals -1/12 because the mathematicians redefined the equal sign. In this style of mathematics, called analytical continuation, "=" stopped meaning “is equal to” and started meaning “is associated with.” Tricky mathematicians. This mathematical trick goes way back, says Physics Central.
Your expression is the same as:
1+(+(+2))
Any numeric expression can be preceded by -
to make it negative, or +
to do nothing (the option is present for symmetry). With negative signs:
1-(-(2)) = 1-(-2) = 1+2 = 3
and
1-(-(-2)) = 1-(2) = -1
I see you clarified your question to say that you come from a C background. In Python, there are no increment operators like ++
and --
in C, which was probably the source of your confusion. To increment or decrement a variable i
or j
in Python use this style:
i += 1 j -= 1
The extra +'s are not incrementors (like ++a or a++ in c++). They are just showing that the number is positive.
There is no such ++ operator. There is a unary + operator and a unary - operator though. The unary + operator has no effect on its argument. The unary - operator negates its operator or mulitplies it by -1.
+1
-> 1
++1
-> 1
This is the same as +(+(1))
1+++2
-> 3 Because it's the same as 1 + (+(+(2))
Likewise you can do --1 to mean - (-1) which is +1.
--1
-> 1
For completeness there is no * unary opeartor. So *1 is an error. But there is a ** operator which is power of, it takes 2 arguments.
2**3
-> 8
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