Python Arithmetic Operators


Introduction to Python Arithmetic Operators

Arithmetic Operators are used to perform common mathematical operations on numbers. These operations are addition, subtraction, multiplication, division, modulus, floor division, and exponential.

OperatorNameExamplePrecedenceAssociativity
+Additiona + b3Left to Right
Subtractiona-b3Left to Right
*Multiplicationa * b2Left to Right
/Divisiona / b2Left to Right
%Modulusa % b2Left to Right
//Floor Divisiona//b2Left to Right
**Exponentiala ** b1Right to Left

Precedence and Associativity

Precedence means priority. When multiple operators are used in a single expression, they are evaluated according to their precedence. Operators are given priority as per PEMDAS.

CharacterFull FormSymbolPriority
PParentheses()1
EExponential**2
MDMultiplication, Division*, /, //, %3
ASAddition, Subtraction+, –4

Associativity, in case we have multiple operators with the same precedence in an expression, they are evaluated as per the associativity. This means the direction we will follow to evaluate them. Only exponential is evaluated from right to left, and all others from left to right.

OperatorAssociativity
**Right to Left
+, -, *, /, //, %Left to Right

Arithmetic Operators

Addition Operator

Python uses the symbol + to perform the addition of values.

In [1]:
x = 7
y = 2
print(x + y)
9

Subtraction Operator

The symbol ‘-‘ is used in Python to perform the subtraction of values.

In [1]:
x = 7
y = 2
print(x - y)
5

Multiplication Operator

Symbol ‘*’ is used as a multiplication operator, to find out the product of values.

In [1]:
x = 8
y = 2
print(x * y)
16

Division Operator

Python uses the symbol ‘/’ to divide the numbers.

Note: In python, even if the numbers are completely divisible, the output is a float.

In [1]:
x = 8
y = 2
print(x / y)
4.0

Division will return float value. Even if output is whole number.

In [2]:
print(type(x / y))
<class 'float'>

Modulus Operator

The symbol ‘%’ is used as the modulus operator. It is used to find out the remainder of the number one divided by the number two.

In [1]:
x = 8
y = 3
print(x % y)
2

Floor division Operator

Floor division is done with the symbol “//” in Python. When the number one is divided by the number two, the result is rounded down to the closest integer value. Because of this, it always returns an integer value.

In [1]:
x = 8
y = 3
print(x // y)
2

Floor Division will always return a smaller integer value.

In [2]:
x = -8
y = 3
print(x // y) #mean 2 to the power 3
-3

Exponential Operator

The symbol ** is an exponential operator, which means ‘raise to the power of’. It will return the left operand raised to the power of the right operand.

In [1]:
x = 2
y = 3
print(x ** y) #mean 2 to the power 3
8

Resources

Handwritten Notes

Python Operators and Arithmetic Operators

References:

  1. Arithmetic Operators
  2. Types of Arithmetic Operators in Python
  3. How to use Python Arithmetic Operators