Python

Python Fundamentals

Operators

print(a / b) # 3.333... — true division (always returns float)

JrCodex·6 min read

Jr Codex Python Notes

Level: Beginner Prerequisites: Chapter 2 Time to complete: ~20 minutes


Table of Contents

  1. Arithmetic Operators
  2. Comparison Operators
  3. Logical Operators
  4. Assignment Operators
  5. Identity vs Equality (is vs ==)
  6. Membership Operators
  7. Operator Precedence
  8. Summary & Next Steps

1. Arithmetic Operators

a, b = 10, 3
 
print(a + b)    # 13  — addition
print(a - b)    # 7   — subtraction
print(a * b)    # 30  — multiplication
print(a / b)    # 3.333... — true division (always returns float)
print(a // b)   # 3   — floor division (rounds down to int)
print(a % b)    # 1   — modulo (remainder)
print(a ** b)   # 1000 — exponentiation
OperatorNameExampleResult
+Addition5 + 27
-Subtraction5 - 23
*Multiplication5 * 210
/True division5 / 22.5
//Floor division5 // 22
%Modulo5 % 21
**Exponent5 ** 225

Common pitfall: / always returns a float, even for exact division — 10 / 2 is 5.0, not 5.


2. Comparison Operators

Return a bool (True/False):

x, y = 5, 10
 
print(x == y)   # False — equal to
print(x != y)   # True  — not equal to
print(x < y)    # True  — less than
print(x > y)    # False — greater than
print(x <= 5)   # True  — less than or equal
print(x >= 6)   # False — greater than or equal

Comparisons chain naturally in Python — a feature many languages don't have:

age = 25
print(18 <= age <= 65)   # True — equivalent to (18 <= age) and (age <= 65)

3. Logical Operators

Combine boolean expressions with and, or, not:

age = 20
has_id = True
 
print(age >= 18 and has_id)   # True  — both must be true
print(age < 18 or has_id)     # True  — at least one true
print(not has_id)             # False — inverts the value
OperatorRule
andTrue only if both operands are True
orTrue if at least one operand is True
notInverts the boolean value

Short-Circuit Evaluation

Python stops evaluating as soon as the result is determined — useful for avoiding errors:

def is_valid(n):
    print("Checking...")
    return n > 0
 
# Second call never happens because first is False
result = False and is_valid(5)   # "Checking..." is NOT printed
 
user = None
# Avoids AttributeError by short-circuiting before accessing user.name
if user and user.name:
    print(user.name)

4. Assignment Operators

Shorthand for updating a variable in place:

count = 10
count += 5    # same as: count = count + 5   → 15
count -= 3    # count = count - 3            → 12
count *= 2    # count = count * 2            → 24
count /= 4    # count = count / 4            → 6.0
count //= 2   # count = count // 2           → 3.0
count **= 2   # count = count ** 2           → 9.0
count %= 4    # count = count % 4            → 1.0
OperatorEquivalent To
x += yx = x + y
x -= yx = x - y
x *= yx = x * y
x /= yx = x / y
x //= yx = x // y
x **= yx = x ** y
x %= yx = x % y

5. Identity vs Equality (is vs ==)

This trips up almost every Python beginner at least once.

a = [1, 2, 3]
b = [1, 2, 3]
c = a
 
print(a == b)   # True  — same VALUES
print(a is b)   # False — different OBJECTS in memory
print(a is c)   # True  — c points to the SAME object as a
Memory Model
─────────────────────────────────────────
  a ──┐
      ├──→ [1, 2, 3]   (object #1)
  c ──┘
  b ──────→ [1, 2, 3]   (object #2, equal VALUE, different OBJECT)
─────────────────────────────────────────

Rule of thumb: use == to compare values (99% of the time). Use is only for identity checks — most commonly is None:

value = None
if value is None:      # ✓ Pythonic — the standard way to check for None
    print("No value set")
 
if value == None:       # works, but not idiomatic — avoid
    pass

6. Membership Operators

in and not in check whether a value exists inside a collection:

fruits = ["apple", "banana", "cherry"]
 
print("banana" in fruits)       # True
print("mango" not in fruits)    # True
 
name = "Alice"
print("A" in name)              # True — works on strings too

We'll use in/not in constantly once we reach lists, dicts, and sets (Chapters 6–9).


7. Operator Precedence

When multiple operators appear in one expression, Python follows a fixed order (highest to lowest):

1. **                (exponentiation)
2. +x, -x, not x      (unary operators)
3. *, /, //, %        (multiplication/division)
4. +, -               (addition/subtraction)
5. ==, !=, <, >, <=, >=, is, in   (comparisons)
6. not
7. and
8. or
result = 2 + 3 * 4        # 14, not 20 — multiplication first
result2 = (2 + 3) * 4     # 20 — parentheses override precedence
result3 = 2 ** 3 ** 2     # 512 — exponent is right-associative: 2 ** (3 ** 2)

Best practice: when in doubt, add parentheses — it costs nothing and removes ambiguity for whoever reads the code next (including future you).


8. Summary & Next Steps

Key Takeaways

  • Arithmetic (+ - * / // % **), comparison (== != < > <= >=), and logical (and or not) operators cover most day-to-day expressions.
  • is checks identity (same object in memory); == checks equality (same value). Use is only for None checks.
  • and/or short-circuit — the second operand may never be evaluated.
  • When precedence gets ambiguous, use parentheses.

Concept Check

  1. Why does 10 / 2 return 5.0 and not 5?
  2. What's the difference between a == b and a is b for two lists with identical contents?
  3. What does 18 <= age <= 65 mean, and is this valid in most other languages?

Next Chapter

Chapter 4: Strings & String Methods


Jr Codex — 1-on-1 Personalized Coaching | Back to Module Index