Python Operators
Learn about different types of operators in Python and how to use them in your programs.
Python Operators
Operators are used to perform operations on variables and values.
In the example below, we use the + operator to add together two values:
Example
print(10 + 5)Python divides the operators in the following groups:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Logical operators
- Identity operators
- Membership operators
- Bitwise operators
Python Arithmetic Operators
Arithmetic operators are used with numeric values to perform common mathematical operations:
Python Assignment Operators
Assignment operators are used to assign values to variables:
Python Comparison Operators
Comparison operators are used to compare two values:
Python Logical Operators
Logical operators are used to combine conditional statements:
Python Identity Operators
Identity operators are used to compare the objects, not if they are equal, but if they are actually the same object, with the same memory location:
Python Membership Operators
Membership operators are used to test if a sequence is presented in an object:
Operator Precedence
Operators evaluate in a fixed order, like maths. When in doubt, add parentheses for clarity.
| Priority | Operators |
|---|---|
| Highest | ** (power) |
* / // % | |
+ - | |
comparisons == != < > | |
not | |
and | |
| Lowest | or |
print(2 + 3 * 4) # 14, not 20 (* before +)
print((2 + 3) * 4) # 20
print(2 ** 3 ** 2) # 512 (** is right-associative: 2 ** 9)is vs == : Identity vs Equality
== asks "are the values equal?"; is asks "are they the same object?". Use is only for None.
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b) # True -> same contents
print(a is b) # False -> different objects
x = None
print(x is None) # True -> the correct way to test for NoneNever write if x == None; always use if x is None.
Chained Comparisons and Walrus
age = 25
print(18 <= age < 65) # True -> chained, reads like maths
# walrus := assigns inside an expression (Python 3.8+)
if (n := len("hello")) > 3:
print(f"{n} characters") # 5 charactersTry It Yourself
Exercise 1: Predict 10 - 2 * 3, then verify.
Show solution
print(10 - 2 * 3) # 4 (multiplication first)Exercise 2: Check whether a number n is between 1 and 10 (inclusive) using a chained comparison.
Show solution
n = 7
print(1 <= n <= 10) # TrueKey Takeaways
- Know precedence:
**>* />+ -> comparisons >and>or. ==compares values;iscompares identity (use forNone).- Comparisons can chain:
1 <= n < 10. - Add parentheses whenever precedence is not obvious.
📘 Real-World Deep Dive
Python's operators are mostly familiar, but a few — <code>**</code>, <code>//</code>, <code>@</code>, walrus — shift how readable your code can be.
Real-Life Scenario
Compute compound interest with monthly contributions, using exponent, floor-division, and the walrus operator.
Real-Life Example
from decimal import Decimal, ROUND_HALF_UP
def yearly_balance(principal: Decimal, monthly: Decimal,
apr: Decimal, years: int) -> Decimal:
monthly_rate = apr / 12
months = years * 12
factor = (1 + monthly_rate) ** months
fv_lump = principal * factor
fv_annuity = monthly * ((factor - 1) / monthly_rate)
return (fv_lump + fv_annuity).quantize(Decimal("0.01"), ROUND_HALF_UP)
import sys
total = Decimal("0")
for line in sys.stdin:
if (amt := Decimal(line.strip() or "0")) >= 0:
total += amt
print("sum =", total.quantize(Decimal("0.01")), file=sys.stderr)Expected Output
sum = 1250.00Common mistakes
/on ints returnsfloatin Python 3 — use//for true integer division or cast toDecimal.-3 ** 2is-9because unary minus binds tighter than**; parenthesise:(-3) ** 2.a is bis only equality forNone,True,False, and small ints — everything else uses==.
🚀 Performance & Best Practices
- Chained comparison
0 < x < 10is faster than0 < x and x < 10and more readable. - The matrix-multiplication operator
A @ Bdispatches to NumPy for arrays — use it instead ofnp.dot. - Walrus (
:=) inside comprehensions and regex matches removes duplicate calls and clarifies intent.
🧪 Try It Yourself
- Add a
--verbosepath that prints monthly balances using the walrus to capture and re-usefactor. - Rewrite
yearly_balancefor yearly compounding and compare the result. - Time
for i in range(n): total += ivs.sum(range(n)); measure at n = 10² and n = 10⁶ and explain the difference.