Python operators expressions

PYTHON Published Updated 2 mins read By Leon Wei
Python operators expressions cover image

Quick summary

Summarize this blog with AI

An expression produces a value; operators help combine its operands. Choose the operation for the objects you actually have: numbers, strings, sets, and pandas Series can give the same symbol different meanings. These examples use Python 3.12.14; the pandas example is checked with pandas 2.2.3 and 3.0.6.

Predict precedence and arithmetic before using a result

print(2 + 3 * 4, (2 + 3) * 4)
print(-2 ** 2, (-2) ** 2, 2 ** 3 ** 2)
print(7 / 2, 7 // 2, -7 // 2, -7 % 2)
print("ab" * 2, [1] + [2])

Expected output:

14 20
-4 4 512
3.5 3 -4 1
abab [1, 2]

Multiplication binds before addition. Exponentiation groups from the right, and -2 ** 2 negates the squared result. Floor division rounds down, including for negatives; it is not truncation toward zero. With a positive divisor, the displayed negative dividend has a nonnegative remainder. Division by zero remains an error.

TaskExpressionImportant boundary
Value equalitya == bMay be elementwise for arrays.
Same objecta is bUse for identity, especially None, not numeric equality.
Scalar conjunctiona and bReturns an operand and short-circuits.
Elementwise conjunction(s > 0) & (s < 10)Parenthesize each comparison.
Assignmentx = valueA statement; == compares.

Compare values, identities, and approximate numbers deliberately

import math
left = [1, 2]
right = [1, 2]
print(left == right, left is right)
print(1 < 2 < 3)
print(0.1 + 0.2 == 0.3, math.isclose(0.1 + 0.2, 0.3))
print([] and "unused", "present" or "fallback")

Expected output:

True False
True
False True
[] present

A chained scalar comparison tests adjacent relationships. Do not transfer that syntax unchanged to a Series, whose truth value is ambiguous. For approximate floating-point calculations, choose tolerances appropriate to the scale; default isclose settings are not a domain policy, especially near zero. Exact money calculations usually need an explicit decimal or integer-unit contract.

Filter pandas rows with elementwise conditions

import pandas as pd
frame = pd.DataFrame({"amount": pd.array([0, 5, 12, None], dtype="Int64"),
                      "status": ["paid", "paid", "paid", "paid"]})
mask = (frame["amount"] > 0) & (frame["amount"] < 10)
print(mask.fillna(False).tolist())
print(frame.loc[mask.fillna(False), "amount"].tolist())
try:
    (frame["amount"] > 0) and (frame["status"] == "paid")
except ValueError:
    print("and requires one truth value, not a Series")

Expected output:

[False, True, False, False]
[5]
and requires one truth value, not a Series

The missing amount yields an unknown nullable Boolean before fillna(False). This report deliberately excludes unknown amounts; it does not prove they are nonpositive. &, |, and ~ operate elementwise here. They are bitwise operators on integers and do not provide scalar short-circuit guards. Parentheses prevent their precedence from binding to the wrong operands.

Read overloaded operations in context

List + concatenates, numeric + adds, and custom classes can define their own behavior. Augmented assignment such as += can mutate a list but rebind an integer name. Use small counterexamples when a result surprises you: a negative number, empty collection, missing value, and equal-but-distinct object expose different mistakes. Never use eval to interpret an untrusted expression as a shortcut for validating input.

References and next steps

Python expressions and precedence, pandas Boolean indexing, Identity versus equality.

Interview Prep

Begin Your SQL, Python, and R Journey

Master 230 interview-style coding questions and build the data skills needed for analyst, scientist, and engineering roles.

Related Articles

All Articles
Python and operator cover image
python Oct 17, 2026

Python and operator

Unravel the role of operators in Python. How they manipulate data values, perform arithmetic, and control program flow, forming the backbone of …

Invalid syntax python cover image
python Oct 17, 2026

Invalid syntax python

Discover Python readable and expressive syntax, the language structure that balances simplicity with flexibility, perfect for both beginners and…

Python mock library cover image
python Apr 29, 2024

Python mock library

Master the Python Mock Library for robust unit testing. Learn to simulate dependencies with Mock, MagicMock, and patch, ensuring reliable and is…

Top python game engines cover image
python Apr 29, 2024

Top python game engines

Explore game creation with Python! Discover how its simplicity & powerful libraries like Pygame and Panda3D make Python a viable choice for indi…

Python main function cover image
python Apr 29, 2024

Python main function

Uncover the best practices for Python's main function, including handling, logging, and debugging. Learn to structure code for clarity and robus…