Operators in Python
Use arithmetic, comparison, logical, assignment, membership, and identity operators correctly.
- Use arithmetic and augmented-assignment operators.
- Compare values with comparison operators.
- Combine conditions with and, or, and not.
- Apply precedence and parentheses to expressions.
- Use membership and identity operators appropriately.
- Explain floor division, modulo, and short-circuit evaluation.
1. Arithmetic operators
The main arithmetic operators are + (addition), - (subtraction), * (multiplication), / (true division), // (floor division), % (modulo), and ** (exponentiation). For ordinary numeric operands, / produces a float result even when the division is exact.
Floor division rounds the mathematical quotient down toward negative infinity. Modulo returns the remainder associated with floor division; with a nonzero divisor, the result has the divisor’s sign.
Floor division and modulo with negatives
print(7 // 3)
print(7 % 3)
print(-7 // 3)
print(-7 % 3)7 divided by 3 has floor quotient 2 and remainder 1. The mathematical quotient -7 / 3 is about -2.333, whose floor is -3. Because the divisor is positive 3, the modulo result is 2, satisfying -7 == (-3 * 3) + 2.
Key Point
| Operator | Meaning | Example result |
|---|---|---|
| + | Addition | 7 + 2 → 9 |
| - | Subtraction | 7 - 2 → 5 |
| * | Multiplication | 7 * 2 → 14 |
| / | True division | 7 / 2 → 3.5 |
| // | Floor division | 7 // 2 → 3 |
| % | Modulo/remainder | 7 % 2 → 1 |
| ** | Exponentiation | 2 ** 3 → 8 |
2. Comparison operators
Comparison operators compare values and produce a Boolean result: ==, !=, <, <=, >, and >=. Use == to compare values for equality and != to check that they differ.
Python also supports chained comparisons, such as 0 <= score <= 100, which means score is at least 0 and at most 100.
Compare values
score = 85
print(score >= 50)
print(score == 100)
print(0 <= score <= 100)85 is at least 50. 85 is not equal to 100. The chained comparison checks both bounds.
3. Logical operators
and is true when both operands are truthy; or is true when at least one operand is truthy; not reverses the truth value. Python evaluates and and or from left to right and uses short-circuit evaluation.
Unlike some languages, and and or return one of their operands, not necessarily a Boolean object. In an if condition this usually works as expected because Python tests truthiness.
Combine conditions
age = 22
has_id = True
print(age >= 18 and has_id)
print(age < 18 or has_id)
print(not has_id)Both parts of the first condition are true. The second condition is true because has_id is true. not True evaluates to False.
Short-circuit evaluation
def check():
print("checked")
return True
print(False and check())
print(True or check())False and ... stops immediately because the result cannot become true; check() is not called. True or ... stops immediately because the result is already true; check() is not called. Therefore checked is never printed.
4. Assignment and augmented assignment
The = operator assigns or rebinds a name. Augmented assignment operators such as +=, -=, *=, and /= combine an operation with assignment. For immutable numeric values, x += 2 is similar in effect to x = x + 2.
For mutable objects, augmented assignment can behave differently from a plain reassignment. For example, list += iterable commonly extends the existing list in place. The exact behavior depends on the object type.
Update a running total
total = 10
total += 5
total *= 2
print(total)total += 5 updates total from 10 to 15. total *= 2 updates it from 15 to 30.
5. Operator precedence and parentheses
Precedence determines which operations group first. For example, multiplication has higher precedence than addition, so 2 + 3 * 4 is evaluated as 2 + (3 * 4). Parentheses can explicitly control grouping and make intent clearer.
Exponentiation ** groups from right to left, so 2 ** 3 ** 2 means 2 ** (3 ** 2), which is 512. Use parentheses when a reader might otherwise have to remember a rule.
Make grouping explicit
print(2 + 3 * 4)
print((2 + 3) * 4)
print(2 ** 3 ** 2)Multiplication happens before addition, giving 14. Parentheses make addition happen first, giving 20. Exponentiation groups from the right, so 2 ** (3 ** 2) equals 512.
6. Membership operators
in tests whether a value is present in a container or sequence; not in tests whether it is absent. For strings, membership checks for a substring. For dictionaries, membership checks keys, not values.
Check membership
colors = ["red", "blue"]
profile = {"name": "Asha", "active": True}
print("red" in colors)
print("green" not in colors)
print("name" in profile)
print("Asha" in profile)red is an element of the list. green is absent from the list. name is a dictionary key. Asha is a dictionary value, not a key.
7. Identity operators
is checks whether two references point to the same object; is not checks that they do not. It is not a replacement for ==. Two separate lists can contain equal values but still be different objects.
A common and appropriate identity check is value is None. Avoid relying on object identity for numbers or strings just because a particular Python run appears to reuse an object.
Equality is not identity
a = [1, 2]
b = [1, 2]
print(a == b)
print(a is b)
result = None
print(result is None)The two lists compare equal by contents. They are separate list objects, so identity is false. is None is the recommended way to test for None.
Common Pitfalls & Mistakes to Avoid
#1 Using / when integer floor division is required.
Explanation: Use // for floor division; note that it rounds down, so -7 // 3 is -3.
#2 Assuming modulo is always positive.
Explanation: For a nonzero divisor, the modulo result has the divisor’s sign; -7 % 3 is 2.
#3 Using is to compare ordinary values.
Explanation: Use == for equality and is for identity, especially checks against None.
#4 Assuming and and or always return True or False.
Explanation: They return an operand and use truthiness to decide whether to evaluate the next operand.
#5 Forgetting operator precedence.
Explanation: Use parentheses when needed to make the intended grouping explicit.
Practice Questions
Set price = 18 and quantity = 4. Calculate total using multiplication, then apply a discount of 5 using augmented assignment. Print the final total.
Given score = 78, print True only if the score is between 0 and 100 inclusive and is at least 40.
Operators in Python Knowledge Check
1. What is the result of -7 // 3?
2. Which operator checks whether two references identify the same object?
3. What is printed by 2 + 3 * 4?
4. In "name" in {"name": "Asha"}, what is being checked?
Technical & Placement Interview Questions
Key Takeaways & Summary
- Know the difference between /, //, %, and **.
- Comparison operators produce Boolean results.
- and and or short-circuit and can return operands.
- Parentheses improve clarity when precedence is not obvious.
- in checks membership; for dictionaries it checks keys.
- Use == for equality and is for object identity.
Finished reading this lesson?
Track your course progress and update your learning dashboard.
Related Topics & Next Steps
Strengthen your programming fundamentals with these related lessons: