Arithmetic Expressions: Precedence and Order
Precedence of Operators
When an expression has multiple operators, Python follows a predefined order of precedence to determine how to evaluate it. For example:
In this case, the // operator (floor division) has higher precedence than - (subtraction), so it is evaluated first.
Precedence Table
**(Exponentiation)*,/,//,%(Multiplication, Division, Floor Division, Modulus)+,-(Addition, Subtraction)
Let's take a more complex example:
Here, the exponentiation (**) is performed first:
Order of Evaluation (Left-to-Right)
Most operators are evaluated from left to right, except for the exponentiation (**) and assignment (=) operators, which are evaluated from right to left.
For example:
This evaluates as:
Another example with modulus (%):
Evaluated as:
However, exponentiation works differently:
This is evaluated from right to left:
Boolean Expressions: Precedence and Order
Basic Boolean Expressions
A simple boolean expression evaluates to True or False:
You can combine multiple conditions using logical operators like and and or:
Precedence and Order of Logical Operators
Similar to arithmetic operators, logical operators follow precedence rules:
not(negation)and(conjunction)or(disjunction)
Logical expressions are evaluated from left to right, but operator precedence affects the order.
For example:
The precedence of not is higher than and, so it's evaluated as:
Another example:
Here, and has higher precedence than or, so it's evaluated as:
Beware of Float Comparisons
Be cautious when comparing floats, as Python uses approximations to represent floating-point numbers. For example:
This is because the float precision rounds the number to 10.0.
Short Circuit Evaluation
Python uses short circuit evaluation to optimize boolean expressions. If the outcome of a logical operation can be determined by the first operand, the second operand is not evaluated.
For example:
No error occurs because Python doesn't evaluate (1 / 0) once it determines that the expression is True.
This behavior applies to and as well. If the first operand is False, the second operand isn't evaluated:
This makes short circuit evaluation useful in avoiding errors in complex expressions.