Different Arithmetic operators in Python
In this tutorial, we will discuss all the basic Arithmetic operators in Python. This is a relatively easy concept. We have used these operations in Mathematics in our school, now we will see how to use these operators in Python to perform basic arithmetic operations.
Table of contents
This operator is used to add two values present on either side of the operator.
x = 2 y = 3 sum = x + y print (sum)
This operator is used to subtract the value present on the right side of the operator from the value present on the left side of the operator.
x = 5 y = 2 sub = x - y print (sub)
This operator is used to find the product of the two values present on either side of the operator.
x = 2 y = 3 mul = x * y print (mul)
This operator is used to find the quotient. The value present on the left side of the operator acts as a Dividend and the one on the right side is Divisor.
x = 5 y = 2 div = x / y print (div)
A division operation always results in a floating-point number.
This operator is used to find the remainder. The value present on the left side of the operator acts as a Dividend and the one on the right side is Divisor.
x = 8 y = 3 mod = x % y print (mod) a = -5 b = 2 res1 = a % b print (res1) m = 5 n = -2 res2 = m % n print (res2)
2 -1 1
The remainder will be positive if the Dividend is positive and vice-versa. Even if the Divisor is negative but the Dividend is positive, the remainder will be positive.
This operator is used to raise the first value to the power of the second operator
x = 2 y = 3 exp = x ** y print (exp)
The Floor Division operator is used to floor the result to the nearest integer.
x = 5 y = 2 flo = x // y print (flo)
Order of precedence of Arithmetic operators in Python
Arithmetic Operators in Python follow a basic order of precedence. When more than one operator is used, they are executed according to this order:
|%, *, /, //||Modulos, Multiplication, Division and Floor division|
|+, -||Addition and Subtraction|
The operator listed at the top of the table will be executed first.
print (((5 + 4) / 3) * 2)
Here, as you can see according to the order of precedence, Parentheses will be computed first. So inside the innermost parenthesis, there is an addition operator.
Closing Thoughts on Arithmetic Operators in Python
We discussed 7 different types of Arithmetic operators in Python. Make sure you remember the order of precedence because that affects the outcome of all operations performed in Python. One can read about other Python concepts here.