🐍 Python Course · Stage 4 · Lesson 61 of 89 · Concept: Operators
Course Overview →

🟩 These concept pages connect Python to programming in general. Read Beginner tab first.

← Concept: Data Types Concept: Control Flow →
thecodex.expert  ·  The Codex Family of Knowledge
CS Concepts

Operators

The symbols that perform computations — and the rules that determine which computation happens first when you combine them.

CS Concepts Requires: Variables ~16 min read Last verified:
Canonical Definition

An operator is a symbol or keyword that represents a computation performed on one or more operands, producing a result — classified by the number of operands (unary, binary, ternary), the type of computation (arithmetic, comparison, logical, bitwise, assignment), and the rules of precedence and associativity that determine evaluation order when operators are combined.

🟩 Beginner

The symbols that do work on values

What you'll learn: Arithmetic, comparison, and logical operators — the operations available in virtually every programming language. Operator precedence (which one goes first when you write 2 + 3 * 4).

How to read this tab: Read alongside writing code. Test each operator in the Python Playground to confirm your predictions.

⏱ 20 min 📄 4 sections 🔶 Prerequisite: Variables
One sentence that captures it

Operators are the verbs of programming: they take values, perform an action, and produce a result.

Two Python-specific operators to memorise: // is floor division (always rounds down: 7 // 2 == 3). % is modulo — the remainder after division (7 % 2 == 1). These are used constantly: // for integer division without fractions, % for checking even/odd (n % 2 == 0) and cycling through values.

Arithmetic operators

The standard arithmetic operators work on numbers: + (add), - (subtract), * (multiply), / (divide), % (modulo — remainder after division), ** or ^ (exponentiation). One subtlety: integer division. In Python 3, 7 / 2 is 3.5 (always a float). 7 // 2 is 3 (floor division, truncates towards negative infinity). In Java and C, 7 / 2 is 3 (integer division, truncates towards zero).

Pythonoperators.py
print(10 + 3)   # 13 — addition
print(10 - 3)   # 7  — subtraction
print(10 * 3)   # 30 — multiplication
print(10 / 3)   # 3.333... — true division (always float)
print(10 // 3)  # 3  — floor division (integer result)
print(10 % 3)   # 1  — modulo (remainder)
print(2 ** 10)  # 1024 — exponentiation

== is equality. = is assignment. Confusing them is the most common beginner error in every language. if x = 5: is a syntax error in Python (deliberately). In C, if (x = 5) silently assigns 5 to x and then evaluates as True — a notorious bug source. Python's design choice here prevents an entire category of mistakes.

Comparison operators

Comparison operators compare two values and return a boolean: == (equal), != (not equal), < (less than), > (greater than), <=, >=. These are the building blocks of all conditional logic — every if statement ultimately evaluates to a boolean.

In Python, == compares values; is compares identity (same object in memory). 1 == 1.0 is True; 1 is 1.0 is False. In JavaScript, == applies type coercion; === checks both value and type. Always use === in JavaScript.

💡

Python's and/or return actual values, not just True/False. x or "default" returns x if x is truthy, otherwise returns "default". x and x.value returns x.value if x is truthy, otherwise returns x (without evaluating x.value). These patterns are used constantly in Python for defaults and safe access.

Logical operators

and / && — true only if both operands are true. or / || — true if at least one operand is true. not / ! — inverts a boolean. These are used to combine conditions in if statements.

Short-circuit evaluation: in A and B, if A is false, B is never evaluated (the result is already false). In A or B, if A is true, B is never evaluated. This is not just an optimisation — it enables common patterns like x is not None and x.value > 0, where evaluating x.value when x is None would raise an error.

📎

Bitwise operators work on individual bits of integers. 5 & 3 is 1 (0101 AND 0011 = 0001). 5 | 3 is 7 (0101 OR 0011 = 0111). Useful for flags and masks (setting/clearing individual bits), network address calculations, and low-level embedded systems. Less common in high-level Python but essential knowledge for working with binary protocols.

Bitwise operators

Bitwise operators work directly on the binary representation of integers: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift). Used heavily in systems programming, cryptography, and flag manipulation.

💡

When in doubt, use parentheses. Operator precedence tables are long and language-specific. The pragmatic rule: if you're not 100% sure, add parentheses. (a + b) * c is unambiguous. Relying on precedence for non-obvious cases makes code harder to read. Parentheses are free.

Precedence: which operation happens first

When multiple operators appear in one expression, precedence rules determine the order of evaluation. 2 + 3 * 4 is 14, not 20, because * has higher precedence than +. This mirrors standard mathematical convention. When in doubt, use parentheses: (2 + 3) * 4 = 20.

General precedence from high to low (most languages): unary (-x, not x) → exponentiation → multiplication/division/modulo → addition/subtraction → comparison → logical AND → logical OR → assignment.

🔵 Intermediate

Precedence, associativity, and short-circuit evaluation

What you'll learn: The full operator precedence table (which operators bind tighter than others). Left vs right associativity. Short-circuit evaluation — why "x is not None and x.value > 0" is safe even if x is None.

How to read this tab: The short-circuit evaluation section is immediately practically useful. Read it and then test: print(None or "fallback"). This pattern appears constantly in Python code.

⏱ 20 min 📄 2 sections 🔶 Prerequisite: Beginner tab
📎

Augmented assignment is a shorthand. x += 1 is (almost always) equivalent to x = x + 1. Python also has -=, *=, /=, //=, %=, **=, &=, |=, ^=. Note: Python has no ++ or -- operators (unlike C, Java, JavaScript). The reason: ++ is easy to confuse with + + in expressions.

Assignment operators and compound assignment

= is assignment (not equality — that is ==). Compound assignment operators combine an operation with assignment: x += 5 means x = x + 5. Available for all arithmetic and bitwise operators in most languages. Python also has the walrus operator := (assignment expression, PEP 572) for assigning inside an expression.

📎

Most operators are left-associative. 10 - 3 - 2 is (10 - 3) - 2 = 5, not 10 - (3 - 2) = 9. The exception: exponentiation is right-associative. 2 ** 3 ** 2 is 2 ** (3 ** 2) = 2 ** 9 = 512, not (2 ** 3) ** 2 = 8 ** 2 = 64.

Precedence and associativity

When two operators of the same precedence appear together, associativity determines evaluation order. Most binary operators are left-associative: 8 - 3 - 2 evaluates as (8 - 3) - 2 = 3, not 8 - (3 - 2) = 7. Exponentiation in Python is right-associative: 2 ** 3 ** 2 = 2 ** (3 ** 2) = 2 ** 9 = 512.

PrecedenceOperators (Python)Associativity
Highest**Right
+x, -x, ~x (unary)
*, /, //, %Left
+, -Left
<<, >>Left
&, ^, |Left
==, !=, <, >, <=, >=, is, in
not
andLeft
LowestorLeft
📎

Python classes can define behaviour for operators. Implement __add__ to define +. Implement __lt__ to define <. This is how Python's built-in types work (strings support + for concatenation, lists support + for joining). The same mechanism lets you write vector1 + vector2 for your own Vector class.

Operator overloading

In many languages, the same operator symbol performs different operations depending on the types of its operands. + adds numbers and concatenates strings. In Python, classes can define custom behaviour for any operator by implementing dunder (double-underscore) methods: __add__ for +, __eq__ for ==, __lt__ for <. NumPy arrays use this to make array + 5 add 5 to every element. C++ allows operator overloading explicitly.

Commonly confused
= is assignment; == is comparison. Writing if x = 5 in Python is a SyntaxError. In C, it compiles — if (x = 5) assigns 5 to x and then evaluates the condition as true (since 5 is truthy). This silent bug is one of the most common C mistakes.
JavaScript's == is not equality — it is coerced equality. 0 == false is true; '' == false is true; null == undefined is true. Use === (strict equality) in JavaScript always.
The modulo operator % is not the same as mathematical modulo for negative numbers. In Python, -7 % 3 is 2 (result has the sign of the divisor — true modulo). In C and Java, -7 % 3 is -1 (result has the sign of the dividend — truncated remainder). These are different operations.
How this connects
Requires first
🔴 Expert

Operator overloading, bitwise ops, and C undefined behaviour

What you'll learn: Operator overloading — how Python lets classes define behaviour for +, -, ==, etc. Bitwise operators for low-level manipulation. C's undefined behaviour with integer overflow.

How to read this tab: The bitwise operators section is relevant for working with binary data, network protocols, or systems programming.

⏱ 20 min 📄 3 sections 🔶 Prerequisite: After Stage 2

Short-circuit evaluation: formal semantics

Short-circuit (lazy) evaluation of logical operators is specified in the language standard, not a compiler optimisation. In Python: and returns the first falsy value, or the last value if all are truthy. or returns the first truthy value, or the last value if all are falsy. These return values, not just booleans: None or "default" returns "default". This is specified in Python Language Reference §6.11.

Undefined behaviour in C integer operations

ISO C17 §6.5: the result of signed integer overflow is undefined behaviour — the compiler may assume it never happens and optimise accordingly. INT_MAX + 1 in C is undefined — not a predictable wrap-around. This enables aggressive optimisations but produces subtle bugs when overflow is assumed. Clang and GCC provide -fsanitize=undefined to detect UB at runtime. Unsigned integer overflow in C is defined: it wraps modulo 2n (ISO C17 §6.2.5p9).

Specification reference

ECMAScript 2024 Language Specification §13 — Expressions; §12.5–12.15. ecma-international.org. Python Language Reference §6 — Expressions. docs.python.org/3/reference/expressions.html. ISO C17 §6.5 — Expressions (operator semantics and undefined behaviour).

How this connects
Requires first
Source confidence: High Last verified: Primary source: ECMAScript 2024 §13 — ECMAScript Language: Expressions

✅ Expert tab complete

  • I know Python uses dunder methods for operator overloading: __add__ for +, __eq__ for ==
  • I know the six bitwise operators: & (AND), | (OR), ^ (XOR), ~ (NOT), << (left shift), >> (right shift)
  • I know that integer overflow is defined in Python (arbitrary precision) but undefined in C

Continue to Control Flow →

Sources

1
ECMAScript 2024 Language Specification (ECMA-262), §13 — Expressions. Ecma International. ecma-international.org. — Authoritative operator semantics for JavaScript.
2
Python Software Foundation. The Python Language Reference, §6 — Expressions. docs.python.org/3/reference/expressions.html. — Operator precedence and short-circuit evaluation semantics.
3
ISO/IEC 9899:2018 (ISO C17). §6.5 — Expressions. International Organization for Standardization. — Formal C operator semantics and signed integer overflow undefined behaviour.