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
- Addition
- Subtraction
- Multiplication
- Division
- Modulus
- Exponentiation
- Floor division
- Order of precedence
- Closing Thoughts
Addition
This operator is used to add two values present on either side of the operator.
Input:
x = 2
y = 3
sum = x + y
print (sum)
Output:
5
Subtraction
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.
Input:
x = 5
y = 2
sub = x - y
print (sub)
Output:
3
Multiplication
This operator is used to find the product of the two values present on either side of the operator.
Input:
x = 2
y = 3
mul = x * y
print (mul)
Output:
6
Division
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.
Input:
x = 5
y = 2
div = x / y
print (div)
Output:
2.5
A division operation always results in a floating-point number.
Modulus
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.
Input:
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)
Output:
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.
Exponentiation
This operator is used to raise the first value to the power of the second operator
Input:
x = 2
y = 3
exp = x ** y
print (exp)
Output:
8
Floor division
The Floor Division operator is used to floor the result to the nearest integer.
Input:
x = 5
y = 2
flo = x // y
print (flo)
Output:
2.0
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:
Operator | Purpose |
---|---|
() | Parentheses |
* | Exponent |
%, , /, // | Modulos, Multiplication, Division and Floor division |
+, - | Addition and Subtraction |
The operator listed at the top of the table will be executed first.
Input:
print (((5 + 4) / 3) * 2)
Output:
6
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.