How do arithmetic and comparison operators work in Python?
· Category: Python Programming
Short answer
Python supports arithmetic operators (+, -, *, /, //, %, **), comparison operators (==, !=, <, >, <=, >=), logical operators (and, or, not), and bitwise operators (&, |, ^, ~, <<, >>).
Steps
- Use arithmetic operators for math.
- Use comparison operators to evaluate conditions.
- Combine conditions with logical operators.
- Use parentheses to control precedence.
# Arithmetic
a = 10 + 3 # 13
b = 10 - 3 # 7
c = 10 * 3 # 30
d = 10 / 3 # 3.333...
e = 10 // 3 # 3 (floor division)
f = 10 % 3 # 1 (modulo)
g = 10 ** 3 # 1000 (exponentiation)
# Comparison
print(a > b) # True
print(a == 13) # True
# Logical
x = 5
print(0 < x < 10) # True (chained comparison)
print(x > 0 and x != 5) # False
print(not x == 10) # True
Tips
- Floor division (
//) always returns a float if either operand is a float. - The
isoperator checks identity, not equality; use==for value comparison. - Python supports chained comparisons like
1 < x < 10. - Bitwise operators work on integers at the binary level and are useful for flags and masks.
Common issues
- Division by zero raises
ZeroDivisionError. - Floating-point comparisons can be imprecise; use
math.isclose()for equality checks. andandorreturn one of the operands, not necessarily a Boolean, which can be surprising.