Python: Mathematical Operators

OperatorDescription
+Addition
Subtraction
*Multiplication
/Division
//Floor division
**Power
%Reminder

Addition

a = 90
b = 23

x = a + 100
y = a + b
z = x + b

print(x)
print(y)
print(z)
Python

Output:

190 
113 
213
Plaintext

Subtraction

a = 90
b = 23

x = a - 100
y = a - b
z = x - b

print(x)
print(y)
print(z)
Python

Output:

-10 
67 
-33
Plaintext

Multiplication

a = 90
b = 23

x = a * 100
y = a * b
z = x * b

print(x)
print(y)
print(z)
Python

Output:

9000 
2070 
207000
Plaintext

Division

a = 90
b = 23

x = a / 100
y = a / b
z = x / b

print(x)
print(y)
print(z)
Python

Output:

0.9 
3.9130434782608696 
0.0391304347826087
Plaintext

Floor Division

a = 90
b = 20

x = a // 10     # 90 / 10 = 9
y = a // b      # 90 / 20 = 4.5
z = x // b      # 9 / 20 = 0.45

print(x)
print(y)
print(z)
Python

Output:

9
4
0
Plaintext

Reminder

a = 90
b = 23

x = a % 8
y = a % b
z = x % b

print(x)
print(y)
print(z)
Python

Output:

2 
21 
2
Plaintext

Power

a = 90
b = 23

x = a ** 3
y = a ** b
z = x ** b

print(x)
print(y)
print(z)
Python

Output:

729000 
886293811965250109592900000000000000000000000 
696198609130885597695136021593547814689632716312296141651066450089000000000000000000000000000000000000000000000000000000000000000000000
Plaintext

Precedence of Mathematical Operators

Not all operators have the same precedence. Based on the operators’ priority/precedence, the evaluation sequence will change.

Let’s check the precedence of the operators and how that affects the evaluation of an expression-

Notes

Expressions are evaluated from Left to Right when they have the same precedence.

Parentheses have the highest priority.
The exponent has the next precedence.
Multiplication, Division, and Reminder are evaluated after that.
Additions and subtractions are evaluated at the end.

Let’s evaluate the following operation-

(3 + 7) * 24 / 2 ** 2 + 6

The operation will be performed as below-

Operator Precedence
Operator Precedence

Let’s check the same thing in code-

calculated_value = (3 + 7) * 24 / 2 ** 2 + 6
# 10 * 24 / 2 ** 2 + 6
# 10 * 24 / 4 + 6
# 10 * 6 + 6
# 60 + 6
# 66

print(calculated_value)
Python

Output:

66.0
Plaintext

Augmented Assignment Operators

We can use the mathematical operators, perform the operation and assign at the same time, by using the following operator

OperatorDescriptionExampleEquivalent Normal Operation
+=Add and assignx += 10x = x + 10
-=Subtract and assignx -= 10x = x – 10
*=Multiply and assignx *= 10x = x * 10
/=Divide and assignx /= 10x = x / 10
//=Floor divide and assignx //= 10x = x // 10
**=Exponenatiate and assignx **= 10x = x ** 10
%=Modulo and assignx %= 10x = x % 10

Leave a Comment


The reCAPTCHA verification period has expired. Please reload the page.