Notifications

No notifications

/Phase 1

Operators & Expressions

Operators & Expressions in Python

Operators are special symbols that perform operations on values (operands). Python supports a rich set of operators for arithmetic, comparison, logic, and more.

Arithmetic Operators

OperatorNameExampleResult
+Addition7 + 310
-Subtraction7 - 34
*Multiplication7 * 321
/Division7 / 32.333...
//Floor Division7 // 32
%Modulus7 % 31
Exponent2 101024

Comparison Operators

OperatorMeaningExample
==Equal5 == 5 → True
!=Not equal5 != 3 → True
<Less than3 < 5 → True
>Greater than5 > 3 → True
<=Less or equal5 <= 5 → True
>=Greater or equal6 >= 5 → True

Logical Operators

OperatorDescriptionExample
andBoth TrueTrue and False → False
orAt least one TrueTrue or False → True
notNegatenot True → False

Assignment Operators

x = 10     # Assign
x += 5     # x = x + 5  → 15
x -= 3     # x = x - 3  → 12
x *= 2     # x = x * 2  → 24
x //= 5    # x = x // 5 → 4

Operator Precedence (High → Low)

**  →  -, +, ~ (unary)  →  *, /, //, %  →  +, -  →  comparisons  →  not  →  and  →  or

On this page

Detailed Theory

Operators are the verbs of programming — add, compare, combine, test. Python keeps them close to maths notation but with a few twists worth knowing (especially / vs //, is vs ==, and short-circuit logic).

What Operators Actually Are

An operator is just a function in disguise. a + b is sugar for a.__add__(b). That's why "hi" + "!" works (string __add__ does concatenation) and why "a" * 3 repeats. Same symbol, different behaviour per type.

The Five Families You'll Use

FamilyOperators
Arithmetic+ - * / // % **
Comparison== != < <= > >=
Logicaland or not
Assignment= += -= *= /= //= %= **=
Identity / Membershipis is not in not in

Learn these well before bitwise.

Arithmetic Subtleties

7 / 2     # 3.5      — true division (always float)
7 // 2    # 3        — floor division
-7 // 2   # -4       — floors toward negative infinity
7 % 2     # 1        — remainder
2 ** 10   # 1024     — power, beats math.pow on ints

/ *always* returns a float in Python 3, even for whole results (4 / 2 is 2.0). Use // when you need an integer.

Beginner Mistakes to Skip

1. a == None. Works but unidiomatic. Use a is None. 2. Comparing floats with ==. Use math.isclose(a, b) because 0.1 + 0.2 != 0.3. 3. a + b across types. "3" + 4 is a TypeError. Convert first. 4. Forgetting operator precedence. a or b and c is a or (b and c). Add parens when in doubt. 5. Using is for value equality on ints/strings. Works for small ints by accident; breaks for big ones. Use ==. 6. x = y = [] then mutating. Both names share the same list — same trap as default args.

Intermediate: Comparison Chaining

Python lets you chain comparisons like in maths:

1 < x < 10           # 1 < x AND x < 10
a == b == c          # all three equal
low <= score < high  # half-open range

Each term is evaluated once, left to right, with short-circuiting. Massively cleaner than 1 < x and x < 10.

Intermediate: Short-Circuit and / or

and returns the first falsy operand (or the last if all truthy). or returns the first truthy operand (or the last if all falsy). The result is the value, not just True/False:

name = user_input or "guest"      # default-fallback idiom
user and user.is_active            # avoids AttributeError if user is None

For strict booleans, use bool(...) explicitly. Modern Python often prefers x if x else default or the walrus operator for clarity.

Intermediate: Augmented Assignment

count += 1                # count = count + 1
items += [4]              # for a list, modifies in place
total *= 1.05             # apply 5% growth

For mutable types (list, set), += may modify in place — watch out when the same list is shared by multiple names.

Intermediate: Identity vs Equality

a = [1, 2]
b = [1, 2]
a == b   # True   — same value
a is b   # False  — different objects
c = a
a is c   # True   — same object

Use is only for *singletons*: None, True, False. Use == for everything else.

Intermediate: Membership in

5 in [1, 2, 5]           # True   — O(n) for lists
"a" in {"a", "b"}        # True   — O(1) for sets / dict keys
"py" in "python"          # True   — substring test

For repeated membership checks on big collections, convert to a set first.

Advanced: Operator Precedence

From highest to lowest (the bits you'll trip over):

**          (power, right-assoc)
+ -         (unary)
  • / // %
+ - (binary) << >> (bit shift) & ^ | (bitwise) == != < ... (comparison + identity + membership) not and or = += ... (assignment, lowest)

When in doubt, parens. Readability beats cleverness.

Advanced: Bitwise Operators

OpMeaningExample
&AND5 & 3 → 1
OR53 → 7
^XOR5 ^ 3 → 6
~NOT~5 → -6
<<left shift1 << 3 → 8
>>right shift8 >> 2 → 2

Real-world: bit flags (PERMS = READ

WRITE), masks, fast pow-of-2 ops, low-level encoding.

Advanced: The Walrus Operator := (Python 3.8+)

Assigns inside an expression. Useful in while and comprehensions:

while (line := f.readline()):
    process(line)

[y for x in data if (y := transform(x)) is not None]

Use sparingly — unreadable code is worse than a bit of duplication.

Advanced: Operator Overloading

Any class can implement __add__, __lt__, __eq__, __contains__, etc., to customise how operators behave on its instances. That's how NumPy makes a + b element-wise and how pathlib makes path / "file.txt" build subpaths.

Practice Path

1. Print the result of 7 / 2, 7 // 2, 7 % 2, 2 ** 10 — confirm the types match your guess. 2. Use chained comparison to validate a score is between 0 and 100 in one line. 3. Implement a default-fallback with or and another with the walrus operator; compare readability. 4. Demonstrate that a is b is unreliable for big ints by trying a, b = 1000, 1000 then a, b = 1000, 10**3.