Operator Precedence Order
Operator precedence determines how Python groups an expression when parentheses do not state the grouping explicitly. This rule describes the grouping. Python evaluates operands from left to right. Precedence determines how operations on those operands are grouped.
Exponentiation treats a unary operator on its right specially: 2 ** -1 means 2 ** (-1) and equals 0.5. By contrast, -2 ** 2 means -(2 ** 2) and equals -4.
Higher-precedence operators bind more tightly. Most binary operators at the same level group from left to right, but exponentiation groups from right to left and comparisons form chains. Parentheses are the clearest choice whenever the intended grouping might be missed.
Comparison Operators
Comparison operators are used to compare two values and produce boolean values (True or False). Comparison operators available in Python:
==equal to!=not equal to<less than<=less than or equal to>greater than>=greater than or equal to
Comparisons of built-in values such as numbers and strings return boolean values. User-defined objects may implement other comparison results. Equality can compare objects of different types, but ordering comparisons such as < require types that define a compatible ordering and may raise TypeError otherwise. Comparisons share a precedence level and can be chained.
# Example of comparison operator usage
>>> 4 == 5
False
>>> 3 > 2.1 # Python supports this mixed numeric comparison
TrueBoolean Operators
Boolean operators combine multiple conditions or modify boolean values. Python provides three main boolean operators:
-
Operator
andreturns the first value if it's false, or the second value if the first value is true. -
Operator
orreturns the first value if it's true, or the second value if the first value is false. -
Operator
notdiffers fromandandoroperators because it always produces a new boolean value.
# Example of boolean operators
>>> 4.0 and 5.0 # 4.0 is truthy, then returns 5.0 without truth-testing 5.0
5.0
>>> 0 and 5 # evaluates 0 as false, returns 0 (short-circuit)
0
>>> 4.0 or 5.0 # evaluates 4.0 as true, returns 4.0 (short-circuit)
4.0
>>> 0 or 5 # 0 is falsy, then returns 5 without truth-testing 5
5
>>> not 4.0 # evaluates 4.0 as true, returns False
False
>>> not 0 # evaluates 0 as false, returns True
TrueThe and and or operators use short-circuit evaluation, meaning evaluation stops when the result can be determined without evaluating all operands. Both return the last evaluated argument, while the not operator always creates a new boolean value.
Values in Boolean Context
Any Python object can undergo truth testing, including objects that are not the values True and False. Python then decides for itself which values count as false. Under that rule an empty list, the number zero, and the empty string all behave like False inside an if, while a non-empty container behaves like True.
Falsy and Truthy Values
These built-in values follow truthiness rules that you can test with bool().
| Group | Falsy examples | Truthy examples |
|---|---|---|
| Boolean | False | True |
| Missing value | None | Not applicable |
| Numbers | 0, 0.0, 0j | -1, 0.5, 2j |
| Strings | "" | "0" |
| Containers | [], {}, (), set() | [0], {"a": 0} |
The string "0" and list [0] remain truthy because they are not empty. The value of an element does not determine the truthiness of its built-in container.
User-defined objects can customize truth testing with __bool__() or __len__(). If neither is defined, an instance is truthy by default.
Boolean Data Type
The bool type in Python represents truth values False and True, is a subtype of integer (int), and booleans behave like and in mathematical operations.
# Bool constructor and arithmetic operations
>>> bool(-1)
True
>>> bool(0.0)
False
>>> True + True
2
>>> 3 * False
0Combining Operators
You can combine comparison operators with boolean operators to create combined conditions. Python also allows more natural comparison chaining like 1 < 2 < 3.
# Example of operator combination
>>> 4.0 > 3 and 2 >= 3 # ⇔ True and False
False
>>> 7 < 6 or 4 != 2 # ⇔ False or True
True
>>> not 0 < 2 # ⇔ not (0 < 2) ⇔ not True
False
# Comparison chaining
>>> 1 < 2 < 3 # ⇔ (1 < 2) and (2 < 3)
True
>>> 5 <= 7 < 10 # ⇔ (5 <= 7) and (7 < 10) --- application: interval test
TrueFloating Point Number Comparison
Many decimal fractions have no exact finite binary floating-point representation. Arithmetic rounds intermediate results, so two mathematically equivalent calculations can produce nearby but unequal floats.
Float Precision Issues
A decimal fraction may require rounding in binary. The diagram distinguishes exactly representable values from values that need rounding.
# Floating point precision problem
>>> a = 0.01
>>> b = 0.1**2 # b is 0.010000000000000002
>>> a == b
False
# Solution with math.isclose()
>>> import math
>>> math.isclose(0.01, 0.1**2)
True
>>> math.isclose(100, 95, rel_tol=0.05) # relative tolerance is 5%
True
>>> math.isclose(100, 95, abs_tol=5) # absolute tolerance is 5
TrueSolution with the Isclose Function
Python provides the math.isclose(a, b, rel_tol=1e-09, abs_tol=0.0) function to test approximate equality. This function uses relative and absolute tolerances through rel_tol and abs_tol to determine whether two values are close enough.
For math.isclose(100, 95, rel_tol=0.05), the absolute difference is 5. Relative tolerance uses the larger absolute value, which is 100.
The difference does not exceed the tolerance, so the result is True. With abs_tol=5, the absolute tolerance of 5 also accepts this difference.
Use exact equality when exact identity of the floating-point value is genuinely required. For measured or calculated quantities, choose tolerances from the problem domain and use
math.isclose(). Near zero, relative tolerance alone shrinks with the compared values, so set anabs_tolthat reflects the smallest meaningful difference.