Arithmetic operators in python
Introduction to Arithmetic Operators in Python
Arithmetic operators are used to perform some common mathematical operations or calculations such as addition(+), subtraction(-), multiplication(*), division(/), and more.
Basic Addition (+):
Adds two operands.
Basic Subtraction (-
):
Subtracts the right operand from the left.
Basic Multiplication (*
):
Multiplies two operands.
Basic Division (/
):
Divides the left operand by the right. The result is always a floating-point number.
Basic Floor Division(//
):
Performs integer division, discarding the remainder.
Basic Modulus(%
):
Returns the remainder of dividing the left operand by the right.
Basic Exponentiation(**
):
Raises the left operand to the power of the right operand.
Understanding Operator Precedence in Python
When you combine multiple arithmetic operations in a single expression, Python needs to decide which operation to perform first. This decision is governed by a set of rules known as operator precedence. If you're familiar with the mathematical order of operations (PEMDAS/BODMAS), then this concept will feel very natural.
In Python, arithmetic operators follow a specific hierarchy from highest to lowest precedence, which determines the order in which expressions are evaluated.
Let’s break it down:
Exponentiation (**
): Highest Precedence
The exponentiation operator has the highest precedence among all arithmetic operators. This means Python evaluates power operations first, even if they appear after other operations in the expression.
Example:
Even though +
appears before **
, exponentiation is evaluated first.
Multiplication (*
), Division (/
), Floor Division (//
), and Modulus (%
): Medium Precedence
These operators come next in the hierarchy. If an expression contains several of these at the same level, they are evaluated from left to right (known as left-associativity).
Example:
Notice that multiplication and division are evaluated before addition, and in the order they appear from left to right.
Addition (+
) and Subtraction (-
): Lowest Precedence
These are the most basic arithmetic operations and are evaluated last unless overridden by parentheses.
Example:
Although addition appears first in the expression, multiplication takes precedence.
Use Parentheses to Control the Order
When in doubt, or when you want to make your intentions crystal clear, use parentheses ()
to override the default precedence and ensure operations are evaluated in the desired order.
Example:
Full Operator Precedence Summary (Highest to Lowest):
Precedence Level | Operators | Description |
---|---|---|
1 (Highest) |
| Exponentiation |
2 |
| Multiplication, Division, Floor Division, Modulus |
3 (Lowest) |
| Addition, Subtraction |