g↗genai/ learner
Python for AI / Lesson 02

Operators

Building reliable AI applications requires computing metrics, partitioning prompt tokens, verifying budgets, and combining logic guards. Python operators are the computational machinery that drives these decisions.

Concept + interactive labBeginner friendly

Arithmetic: Chunks, remainders, and powers.

In AI engineering, you constantly compute token counts, divide long documents into chunks for embedding, and scale model architecture parameters. Python provides a dedicated set of arithmetic operators to handle each scenario.

While addition (+), subtraction (-), and multiplication (*) behave like standard calculator math, division has three distinct forms that every AI practitioner must master:

# The three division operators in Python:

ratio = 1350 / 500 # True division: always float 2.7

chunks = 1350 // 500 # Floor division: integer 2 full chunks

leftover = 1350 % 500 # Modulo: integer 350 tokens remaining

Key misconception — True division always produces a float: Even when numbers divide evenly without a remainder, single slash (/) returns a float. For example, 10 / 2 evaluates to 5.0, not the integer 5.

When partitioning a 1,350-token document into 500-token chunks for a RAG pipeline, floor division (//) tells you how many full chunks you have, and modulo (%) tells you how many leftover tokens must go into the final tail chunk:

Full chunks (// floor division)
Remainder tokens (% modulo)
/ (True division)float
1350 / 500 = 2.7

Always gives a float. Represents the exact fractional ratio of chunks.

// (Floor division)int
1350 // 500 = 2

Counts complete chunks that fit into the total without any fraction.

% (Modulo)int
1350 % 500 = 350

Gives leftover tokens remaining after all full chunks are extracted.

Mathematical relationship: In Python, (1350 // 500) * 500 + (1350 % 500) == 1350 evaluates to True. The full chunks and remainder perfectly reconstruct the original total.
How Python partitions a 1,350-token document with a 500-token chunk size: floor division (//) yields 2 full chunks, modulo (%) yields 350 leftover tokens, and true division (/) yields 2.7.

Notice how floor division and modulo complement each other:

  • // gives the integer quotient (rounds towards negative infinity). If both operands are integers, the result is an int. If either operand is a float (e.g. 1350.0 // 500), Python returns a float (2.0).
  • % gives the integer remainder left over after all full chunks are accounted for.
  • (chunks * chunk_size) + leftover == total is an exact identity that reconstructs the original document length.

Powers and dimensions: ** versus ^

In AI, model dimensions, vocabulary sizes, and context limits are routinely powers of two (e.g. 28 = 256, 210 = 1,024, 212 = 4,096).

In Python, the exponentiation operator is double asterisk (**):

# Compute a 1024-token context window

context_limit = 2 ** 10 # 1024

Warning — The caret (^) is NOT power in Python: In mathematics, people write 2^10. In Python, the caret ^ is the bitwise XOR operator. Running 2 ^ 10 evaluates to 8, not 1024! Always use ** for exponentiation.
Infographic illustrating Python operators for AI pipelines in three panels: Division trio showing 1350 tokens partitioned into two 500-token chunks and 350 remainder tokens; Powers versus XOR showing 2 ** 10 = 1024 contrasted with bitwise 2 ^ 10 = 8; and Assignment versus Equality showing count = 500 assigning a value and count == 500 evaluating to True.
Core operator mental model: true division produces floats, floor division and modulo partition chunks and remainders, ** scales powers (while ^ is bitwise XOR), and == compares values without mutating variables.

Comparisons: Evaluating truth and thresholds.

AI scripts constantly evaluate thresholds before calling an API: Does the prompt fit in our token budget? Did the model return high confidence? Is the finish reason valid?

Comparison operators inspect values and return a bool (True or False):

# Threshold comparisons in AI workflows

within_budget = 1350 <= 1024 # False

has_tail = 350 > 0 # True

is_standard = 500 == 500 # True

Key misconception — Assignment (=) versus Equality (==): A single equals sign (=) assigns a value to a variable name. A double equals sign (==) compares two values and returns True or False. Writing chunk_size = 500 overwrites the variable, while chunk_size == 500 inspects it without changing it.

Python provides six core comparison operators:

  • == (equal to) and != (not equal to)
  • < (strictly less than) and <= (less than or equal to)
  • > (strictly greater than) and >= (greater than or equal to)

Boolean logic: Combining guards with and, or, not.

Real-world AI pipelines often require multiple conditions to be met simultaneously before making a costly LLM call. Python provides three logical operators: and, or, and not.

# Combining pipeline safety checks

can_process_directly = (total_tokens <= 1024) and (total_tokens > 0)

needs_warning = (total_tokens > 1024) or (total_tokens <= 0)

is_safe = not (total_tokens > 1024)

Python evaluates logical operators using two fundamental principles:

  • Short-circuit evaluation: In an and expression, if the left operand is False, Python immediately returns False without evaluating the right operand. In an or expression, if the left operand is True, Python immediately returns True.
  • Grouping with parentheses: While Python has built-in precedence (not binds tighter than and, which binds tighter than or), production AI teams do not rely on memorizing precedence tables. Wrap each comparison in parentheses (...) so the logic is unambiguous to readers and debuggers.

Inspect operators in the AI pipeline sandbox.

Test different document sizes and observe how arithmetic, comparisons, and boolean guards behave interactively.

Try it in this order:
  1. Select the Division & Chunks tab. Observe that 1350 / 500 gives 2.7 (float), 1350 // 500 gives 2 (int), and 1350 % 500 gives 350 (int).
  2. Toggle Type: float to see how // produces 2.0 (float) when given float operands.
  3. Switch to Powers vs XOR. Compare 2 ** 10 (1024) with 2 ^ 10 (8) to see why the caret is not a power operator.
  4. Switch to Thresholds & Equality and verify that comparisons evaluate to bool.
  5. Switch to Boolean Guards to trace how step-by-step short-circuiting works with and, or, and not.

AI Pipeline Operator Sandbox

Interactive Lab
Presets
Adjust Pipeline Parameters
Total: 1350 tokens
Operator Category
/ True divisionfloat
1350 / 500 = 2.70

Always returns a float, even if the division is perfectly exact.

// Floor divisionint
1350 // 500 = 2

Counts completed chunks. Both operands are int, so result is int 2.

% Moduloint
1350 % 500 = 350

Leftover tokens remaining in the partial final chunk.

chunks = 1350 // 500 # 2
remainder = 1350 % 500 # 350

Reconstruction identity: (2 * 500) + 350 == 1350 evaluates to True.

✎ Try it yourselfKnowledge check · Practice only

Check your understanding.

An AI document chunker receives a document of 1350 tokens and splits it into chunks of 500 tokens. Which Python expression correctly calculates the number of leftover tokens in the final incomplete chunk?
THE TAKEAWAY

Take this with you.

Division in Python has three distinct tools: true division (/) always returns a float, floor division (//) calculates completed integer chunks, and modulo (%) isolates leftover remainders. For powers, always use **; never use ^ (which is bitwise XOR). Comparisons (==, !=, <=, etc.) produce booleans, and double equals (==) tests equality without modifying the variable. Group boolean guards with explicit parentheses (...) for readable and reliable code.

Next up: Strings in Chapter P1 →