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.
Operator | Name | Example | Precedence | Associativity |
---|---|---|---|---|
+ | Addition | a + b | 3 | Left to Right |
– | Subtraction | a-b | 3 | Left to Right |
* | Multiplication | a * b | 2 | Left to Right |
/ | Division | a / b | 2 | Left to Right |
% | Modulus | a % b | 2 | Left to Right |
// | Floor Division | a//b | 2 | Left to Right |
** | Exponential | a ** b | 1 | Right 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.
Character | Full Form | Symbol | Priority |
---|---|---|---|
P | Parentheses | () | 1 |
E | Exponential | ** | 2 |
MD | Multiplication, Division | *, /, //, % | 3 |
AS | Addition, 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.
Operator | Associativity |
---|---|
** | Right to Left |
+, -, *, /, //, % | Left to Right |
Arithmetic Operators
Addition Operator
Python uses the symbol + to perform the addition of values.
x = 7
y = 2
print(x + y)
Subtraction Operator
The symbol ‘-‘ is used in Python to perform the subtraction of values.
x = 7
y = 2
print(x - y)
Multiplication Operator
Symbol ‘*’ is used as a multiplication operator, to find out the product of values.
x = 8
y = 2
print(x * y)
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.
x = 8
y = 2
print(x / y)
Division will return float value. Even if output is whole number.
print(type(x / y))
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.
x = 8
y = 3
print(x % y)
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.
x = 8
y = 3
print(x // y)
Floor Division will always return a smaller integer value.
x = -8
y = 3
print(x // y) #mean 2 to the power 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.
x = 2
y = 3
print(x ** y) #mean 2 to the power 3