1 Hour

4. Operators & Expressions

Module 04: Operators & Expressions

The math and logic your code runs on

These work exactly like math. No tricks here — just clean, simple calculation:

Python 3
a = 10
b = 3

print(a + b)   # Addition:       13
print(a - b)   # Subtraction:    7
print(a * b)   # Multiplication: 30
print(a / b)   # Division:       3.333...
print(a // b)  # Floor Division: 3  (no remainder)
print(a % b)   # Modulo:         1  (the remainder)
print(a ** b)  # Exponentiation: 1000  (10 to the power of 3)

The modulo operator (%) is incredibly useful. It tells you the remainder after division. Use cases: checking if a number is even (n % 2 == 0), cycling through values, clock math.

Comparison Operators

Comparison operators compare two values and return a Boolean (True or False):

Python 3
x = 10
y = 20

print(x == y)   # Equal to:              False
print(x != y)   # Not equal to:          True
print(x > y)    # Greater than:          False
print(x < y)    # Less than:             True
print(x >= 10)  # Greater or equal:      True
print(x <= 5)   # Less or equal:         False
Critical Mistake

= means assignment (store a value). == means comparison (are these equal?). Confusing them is one of the most common beginner bugs.

Logical Operators

Logical operators combine Boolean values — they're the and, or, not of programming:

Python 3
age = 20
has_id = True

# AND — both must be True
can_enter = (age >= 18) and has_id
print(can_enter)  # True

# OR — at least one must be True
is_weekend = False
is_holiday = True
day_off = is_weekend or is_holiday
print(day_off)    # True

# NOT — flips the boolean
is_locked = False
print(not is_locked)  # True

Assignment Operators

These modify and assign in one step — shorthand for common operations:

Python 3
score = 100

score += 10   # Same as: score = score + 10  → 110
score -= 20   # Same as: score = score - 20  → 90
score *= 2    # Same as: score = score * 2   → 180
score //= 3   # Same as: score = score // 3  → 60
score **= 2   # Same as: score = score ** 2  → 3600

Operator Precedence

Just like in math, operators have a priority order. Python follows PEMDAS (Parentheses, Exponents, Multiplication/Division, Addition/Subtraction):

Python 3
# Precedence in action
result = 2 + 3 * 4      # = 14, not 20 (multiplication first)
result = (2 + 3) * 4    # = 20 (parentheses override)
result = 2 ** 3 + 1     # = 9 (exponent before addition)

# When in doubt, use parentheses to make intent explicit
is_valid = (age >= 18) and (score > 50) and (not is_banned)

Rule of thumb: when in doubt about precedence, just add parentheses. They're free, and they make your code clearer to anyone reading it — including future you.

Knowledge Check

Ready to test your understanding of 4. Operators & Expressions?

Back