Arithmetic Operators in Python


☞ For basic calculations we use arithmetic operators. Arithmetic Operators are :

**  ➺    exponent
/   ➺    division
//  ➺    floor division
*   ➺    multiplication
%   ➺    modulus
+   ➺    addition
-   ➺    subtraction

☞ For their precedence and associativity see its table which we have seen in above section.

☞ All the arithmetic operators are binary operators except + and -.

☞ + and - are unary as well as binary operators.


Unary Operators ( +, - )

☞ Unary operators act on one operand.

☞ Example :

a=10    +a means 10 whereas -a means -10
b=-20   +b means -20 whereas -b means 20

Example

a=10
print(a,-a)
b=-20
print(b,-b)

Output

10 -10
-20 20

Binary Operators ( **, +, -, /, //, %, * )

☞ Binary operators act upon two operands.

☞ Example : c = a + b


Exponent **

Example

print(2**3)
print(5**2**2)
print(10**-3)
print((-2)**4)
print(-2**4)
print(-2**-2)
print((-2)**-2)
print(2**0.5)
print(2.5**4)
print(20**20)

Output

8
625
0.001
16
-16
-0.25
0.25
1.4142135623730951
39.0625
104857600000000000000000000

Division /

Example

print(3/4)
print(-3/-4)
print(-3/4)
print(3/-4)
print("---------")
print(3.0/4.0)
print(-3.0/-4.0)
print(-3.0/4)
print(3/-4.0)

Output

0.75
0.75
-0.75
-0.75
---------
0.75
0.75
-0.75
-0.75
Note :
1. It gives float value i.e. output will be in decimal.
2. If numerator and denominator will be positive or negative, then output will be positive.

Floor Division //

Example

print(3//4)
print(-3//-4)
print(-3//4)
print(3//-4)
print("---------")
print(3.0//4.0)
print(-3.0//-4.0)
print(-3.0//4)
print(3//-4.0)

Output

0
0
-1
-1
---------
0.0
0.0
-1.0
-1.0
Note :
1. It gives floor value i.e. only the whole part of the result is given in the output and the fractional part is truncated.
2. If numerator and denominator will be positive or negative, then output will be positive.

Modulus %

Example

print(5%8)
print(-5%-8)
print(8%5)
print(-8%-5)
print("---------")
print(5.0%8.0)
print(-5.0%-8.0)
print(8.0%5.0)
print(-8.0%-5.0)
print("---------")
print(-5%8)
print(5%-8)
print(-8%5)
print(8%-5)

Output

5
-5
3
-3
---------
5.0
-5.0
3.0
-3.0
---------
3
-3
2
-2
Note :
1. It gives remainder.
2. If denominator is negative, then output will be negative.
3. To get the answer of -5 % 8, 5 % -8, -8 % 5, 8 % -5, just read the table until you got the multiple >= numerator, and then subtract the numerator by that multiple.

Multiply *, Addition +, subtraction -

Example

print(5 * 8)
print(-5 * -8)
print(8 * -5)
print(-8 * 5)
print("---------")
print(5 + 8)
print(-5 + -8)
print(8 +  -5)
print(-8.0 + 5)
print("---------")
print(5 - 8)
print(-5 - -8)
print(8 -  -5)
print(-8.0 - 5)

Output

40
40
-40
-40
---------
13
-13
3
-3.0
---------
-3
3
13
-13.0

Augmented Assignment Operators ( **, +, -, /, //, %, * )

☞They also act upon two operands but its declaration is different.

☞Example : a += b which means a = a + b, a *= b which means a = a * b, etc