Python Operators
// and modulo %), operator precedence, and how to combine operators in real expressions.
Arithmetic Operators
Arithmetic operators perform mathematical calculations. Python has 7 of them — you know most from school, but two are unique to programming.
| Operator | Name | Example | Result |
|---|---|---|---|
| + | Addition | 10 + 3 | 13 |
| - | Subtraction | 10 - 3 | 7 |
| * | Multiplication | 10 * 3 | 30 |
| / | Division (always float) | 10 / 3 | 3.333… |
| // | Floor Division (integer result) | 10 // 3 | 3 |
| % | Modulo (remainder) | 10 % 3 | 1 |
| ** | Exponentiation (power) | 2 ** 10 | 1024 |
/ always returns a float — even for whole numbers10 / 2 returns 5.0, not 5. If you need an integer result, use //. This is a common source of bugs when you expect an int and get a float instead.a, b = 17, 5 print(a + b) # 22 — addition print(a - b) # 12 — subtraction print(a * b) # 85 — multiplication print(a / b) # 3.4 — true division (always float!) print(a // b) # 3 — floor division (discard remainder) print(a % b) # 2 — modulo (the leftover: 17 = 5×3 + 2) print(a ** b) # 1419857 — 17 to the power of 5 # Real-world uses of // and % minutes = 137 print(f"{minutes // 60}h {minutes % 60}m") # 2h 17m number = 42 print(number % 2 == 0) # True — even numbers have remainder 0 # Negative floor division — rounds toward negative infinity print(-7 // 2) # -4 (not -3 — always rounds DOWN) print(7 // -2) # -4
% is incredibly usefuln % 2 == 0), converting minutes to hours/minutes, cycling through values (e.g. keeping a counter within 0–6 for days of the week), and validating things like credit card checksums. It's one of the most important operators to master.Comparison Operators
Comparison operators compare two values and always return a boolean — either True or False. They are the backbone of every if statement and loop condition you'll ever write.
= assigns — == compares. Never confuse them.x = 5 stores 5 in x. x == 5 checks if x equals 5. Using = inside an if condition is a SyntaxError in Python (unlike some other languages). This is Python protecting you from a classic bug.age = 20 print(age >= 18) # True — is adult? print(age == 21) # False — exact match print(age != 21) # True — not equal # Chained comparisons — very Pythonic! score = 75 print(60 <= score <= 100) # True — is it between 60 and 100? # Comparing strings (alphabetical order) print("apple" < "banana") # True — 'a' comes before 'b' print("Python" == "python") # False — case-sensitive! # None comparisons — always use is, not == result = None print(result is None) # True — correct way print(result == None) # True — works but bad practice
Logical Operators
Logical operators combine multiple boolean expressions. Python uses English words (and, or, not) instead of symbols like && and || used in other languages — making conditions much more readable.
and — Both must be TrueTrue and True → TrueTrue and False → FalseBoth conditions required
or — At least one TrueTrue or False → TrueFalse or False → FalseOnly one needs to pass
not — Flips the valuenot True → Falsenot False → TrueInverts any boolean
A and B, if A is False, B is never checked. In A or B, if A is True, B is skipped.age = 22 has_id = True is_member = False # and — both conditions required print(age >= 18 and has_id) # True (22≥18 AND has ID) print(age >= 18 and is_member) # False (22≥18 BUT not member) # or — at least one condition required print(has_id or is_member) # True (has ID, even if not member) print(not has_id or is_member) # False (neither True) # not — invert print(not is_member) # True (flip False) print(not (age < 18)) # True (22 is not < 18) # Combined — grade checker score = 78 passed = score >= 50 distinction = score >= 75 and passed print(f"Passed: {passed}, Distinction: {distinction}") # Passed: True, Distinction: True
Assignment Operators
You already know = for assigning values. Python also has augmented assignment operators that combine an arithmetic operation with assignment in one step.
| Operator | Equivalent to | Example (x=10) | Result |
|---|---|---|---|
| += | x = x + n | x += 3 | x = 13 |
| -= | x = x - n | x -= 3 | x = 7 |
| *= | x = x * n | x *= 3 | x = 30 |
| /= | x = x / n | x /= 4 | x = 2.5 |
| //= | x = x // n | x //= 3 | x = 3 |
| %= | x = x % n | x %= 3 | x = 1 |
| **= | x = x ** n | x **= 2 | x = 100 |
# Simulating a game score counter score = 0 score += 10 # player hits enemy → 10 score += 25 # player levels up → 35 score -= 5 # player takes damage → 30 score *= 2 # double-points bonus → 60 print(score) # 60 # Using //= to keep a whole number total_seconds = 3661 hours = total_seconds // 3600 remain = total_seconds % 3600 minutes = remain // 60 seconds = remain % 60 print(f"{hours}h {minutes}m {seconds}s") # 1h 1m 1s
Identity & Membership Operators
Two more operator categories complete the picture. You've already seen in with strings — it works on all Python collections.
| Operator | Category | Meaning | Example |
|---|---|---|---|
| is | Identity | Same object in memory (not just equal value) | x is None |
| is not | Identity | Not the same object in memory | x is not None |
| in | Membership | Value exists in a sequence | "a" in "cat" |
| not in | Membership | Value does NOT exist in a sequence | 7 not in [1,2,3] |
# is / is not — use only for None, True, False user = None print(user is None) # True — idiomatic Python print(user is not None) # False # in — works on strings, lists, tuples, dicts print("py" in "python") # False — case-sensitive! print("Py" in "Python") # True print(3 in [1, 2, 3, 4]) # True print(5 not in [1, 2, 3]) # True # Practical: check allowed roles role = "editor" allowed = ["admin", "editor", "moderator"] print(role in allowed) # True — role is permitted
Operator Precedence
When an expression has multiple operators, Python evaluates them in a specific order of precedence — like BODMAS/PEMDAS in mathematics. Higher rank = evaluated first. When in doubt, use parentheses to make intent explicit.
# Without parentheses — follows precedence rules print(2 + 3 * 4) # 14 (* before +) print(10 - 2 ** 3) # 2 (** before -) print(6 / 2 * 3) # 9.0 (left to right when same level) # With parentheses — override precedence print((2 + 3) * 4) # 20 (+ first now) print((10 - 2) ** 3) # 512 (subtraction first) # Complex expression — use parens for readability x = 5 # confusing: # clear: print(x ** 2 + 2 * x + 1) # 36 — (x+1)² = 6² = 36 print((x ** 2) + (2 * x) + 1) # 36 — same, but crystal clear # Logical precedence trap print(True or False and False) # True (and before or) print((True or False) and False) # False (parens change result!)
(age >= 18) and (has_ticket) is clearer than age >= 18 and has_ticket even though both produce the same result.17 % 5 return?10 / 2 return in Python 3?2 + 3 * 4 evaluate to?not (5 > 3) return?1. Stores marks for 3 subjects as integers
2. Calculates the total and percentage (out of 300)
3. Uses
// to get the integer part of the percentage4. Uses
% to check if the total is exactly divisible by 35. Uses comparison operators to assign a letter grade: A (≥80%), B (≥65%), C (≥50%), F (below 50%)
6. Uses logical operators to check if the student both passed (≥50%) AND scored above 60 in all 3 subjects
7. Prints a formatted result card using an f-string
💡 Show hints
- Percentage:
(total / 300) * 100— ortotal * 100 // 300for integer - For letter grade, use if/elif/else (preview of next phase!)
- Divisible by 3:
total % 3 == 0 - All passed:
s1 > 60 and s2 > 60 and s3 > 60
# ── Smart Grade Calculator ──────────────────── math = 78 english = 85 science = 72 total = math + english + science # 235 percentage = total * 100 // 300 # 78 (integer) div_by_3 = total % 3 == 0 # False # Letter grade if percentage >= 80: grade = "A" elif percentage >= 65: grade = "B" elif percentage >= 50: grade = "C" else: grade = "F" all_passed = math > 60 and english > 60 and science > 60 print(f""" ╔══════════════════════════╗ Result Card Math : {math} English : {english} Science : {science} ────────────────────────── Total : {total} / 300 Percent : {percentage}% Grade : {grade} Div/3 : {div_by_3} All 60+ : {all_passed} ╚══════════════════════════╝""")