🌱 Phase 1 · Foundations 🟢 Beginner MODULE 04

Python Operators

⏱️ 30 min read
📖 Theory + Code
🧩 5 Quiz Questions
🏗️ 1 Challenge
Your progress in Phase 167%
🎯 What you'll learn: All 5 categories of Python operators — arithmetic, comparison, logical, assignment, and identity/membership — plus the two most confusing ones (floor division // 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.

OperatorNameExampleResult
+Addition10 + 313
-Subtraction10 - 37
*Multiplication10 * 330
/Division (always float)10 / 33.333…
//Floor Division (integer result)10 // 33
%Modulo (remainder)10 % 31
**Exponentiation (power)2 ** 101024
💡
/ always returns a float — even for whole numbers
10 / 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.
arithmetic.py
PYTHON
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
Modulo % is incredibly useful
The modulo operator is used for: checking if a number is even/odd (n % 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.

<
Less than
3 < 5 → True
>
Greater than
5 > 3 → True
==
Equal to
5 == 5 → True
!=
Not equal
5 != 3 → True
<=
Less or equal
5 <= 5 → True
>=
Greater or equal
6 >= 5 → True
⚠️
= 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.
comparison.py
PYTHON
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 True
True and True → True
True and False → False
Both conditions required
or — At least one True
True or False → True
False or False → False
Only one needs to pass
🔄
not — Flips the value
not True → False
not False → True
Inverts any boolean
Short-circuit evaluation
Python stops as soon as the result is known. In A and B, if A is False, B is never checked. In A or B, if A is True, B is skipped.
logical.py
PYTHON
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.

OperatorEquivalent toExample (x=10)Result
+=x = x + nx += 3x = 13
-=x = x - nx -= 3x = 7
*=x = x * nx *= 3x = 30
/=x = x / nx /= 4x = 2.5
//=x = x // nx //= 3x = 3
%=x = x % nx %= 3x = 1
**=x = x ** nx **= 2x = 100
assignment.py
PYTHON
# 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.

OperatorCategoryMeaningExample
isIdentitySame object in memory (not just equal value)x is None
is notIdentityNot the same object in memoryx is not None
inMembershipValue exists in a sequence"a" in "cat"
not inMembershipValue does NOT exist in a sequence7 not in [1,2,3]
identity_membership.py
PYTHON
# 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.

1
( )
Parentheses — highest priority
2
**
Exponentiation
3
+x, -x
Unary plus/minus
4
*, /, //, %
Multiplication, division, floor-div, modulo
5
+, -
Addition, subtraction
6
<, >, <=, >=, ==, !=
Comparisons
7
not
Logical NOT
8
and
Logical AND
9
or
Logical OR — lowest priority
precedence.py
PYTHON
# 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!)
🎭
Rule of thumb: when in doubt, parenthesise
Even experienced Python developers add parentheses to make complex expressions readable — not just to override precedence, but as documentation. (age >= 18) and (has_ticket) is clearer than age >= 18 and has_ticket even though both produce the same result.
🧩 Knowledge Check
5 questions — test your understanding of Python Operators
1. What does 17 % 5 return?
2. What does 10 / 2 return in Python 3?
3. What does 2 + 3 * 4 evaluate to?
4. What does not (5 > 3) return?
5. Which operator checks if two variables point to the same object in memory?
🏗️
Coding Challenge — Smart Grade Calculator
Use arithmetic, comparison, and logical operators together
Task: Write a grade calculator that:

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 percentage
4. Uses % to check if the total is exactly divisible by 3
5. 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 — or total * 100 // 300 for 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
grade_calculator.py — Sample Solution
PYTHON
# ── 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}
╚══════════════════════════╝""")
🎉
Lesson 4 Complete!
You've mastered all Python operators. One more lesson before your first mini projects!
← Course Home
Phase 1 · FoundationsLesson 4 of 6