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