Python - Operators
Overview
Estimated time: 20–30 minutes
Use Python operators effectively and readably.
Learning Objectives
- Use arithmetic, comparison, and assignment operators.
- Use logical, membership, and identity operators.
- Know operator precedence and use parentheses for clarity.
Prerequisites
Operator examples
a, b = 3, 5
print(a + b, a * b, a ** b)
print(a == b, a != b, a < b)
print((a < b) and (b < 10))
print("py" in "python")
print(a is a, a is not b)
Precedence
# Always add parentheses for readability
result = (a + b) * (a - b)
Common Pitfalls
- Using
is
for value equality instead of identity (use==
for values). - Forgetting that
and
/or
return operands, not booleans.
Checks for Understanding
- When should you use
is
? - What does
"x" in "exam"
evaluate to?
Show answers
- For identity comparisons (e.g.,
x is None
). True
Exercises
- Write an expression that checks if a number is between 1 and 10 inclusive.
- Show how precedence can change a result without parentheses.