sandeep kasaragod
sandeep kasaragod

Reputation: 17

How does Python execute the arithmetic operation if multiple operations are found in a single statement

I need to know how Python executes arithmetic operations. Below I have given some of the question. Please explain the concept behind this.

why 3+-+--2 = 1
why  3+-+-+--+++2 = 1
why 3-----------2 = 1
why 3--------+2 = 5

Upvotes: 1

Views: 177

Answers (1)

Lav
Lav

Reputation: 2274

When investigating such things, it helps to start small and advance from there. If you try these expressions one by one, it's pretty easy to see how it works:

3-2 = 1
3--2 = 5
3---2 = 1
3----2 = 5

Essentially, the first operation is applied to two operands, all other +s or -s are stacked on right operand as unary operations (as "positive" and "negative" conversions respectively). You can also use ~ operation (binary negative). There are no other unary operators in Python, so you're limited to these three (technically, abs() is a unary operation as well, but it's implemented as a function call instead of operator, so you can't stack it like this).

Internally, these operations are interpreted as calls to x.__pos__(), x.__neg__() and x.__invert__() special methods. See Python docs on special methods for more details.

To understand how such expressions are processed by Python, you can encase everything to the right of first operator in brackets and then use standard arithmetic rules to calculate:

3+-2 = 3+(-2) = 1
3+--2 = 3+(--2) = 3+(-(-2)) = 3+2 = 5
3--+2 = 3-(-+2) = 3-(-(+2)) = 3-(-2) = 3+2 = 5

Of course, if you find yourself writing expressions like 3+----+~+-2, there's something really wrong with your code, but I assume your question is theoretical. :-)

Upvotes: 3

Related Questions