Skip to content

Operators in Depth

Operators are the verbs of the programming world. They take data (operands) and perform actions on them to produce new values. While basic math is straightforward, Python’s operators have unique behaviors—like floor division and short-circuit logic—that are essential for writing robust code.


Python handles math with high precision, but you must understand the difference between the two types of division.

SymbolOperationBehaviorExample
+AdditionSums values.5 + 2 = 7
-SubtractionFinds difference.5 - 2 = 3
*MultiplicationFinds product.5 * 2 = 10
/True DivisionAlways returns a float.5 / 2 = 2.5
//Floor DivisionReturns the integer part (rounds down).5 // 2 = 2
%ModulusReturns the remainder.5 % 2 = 1
**ExponentiationPower of (x to the y).5 ** 2 = 25

A common pitfall is assuming // just “chops off” the decimal. It actually rounds down towards negative infinity.

print(-7 // 2) # Output: -4 (not -3!)

Comparison operators evaluate the relationship between two values and return a bool.

OperatorMeaning
==Equal value
!=Not equal
> / <Greater / Less than
>= / <=Greater / Less or equal

Python allows you to write mathematical ranges just like you would on paper. This is more readable than using and.

chaining.py
age = 25
# Standard way: if age >= 18 and age <= 65:
# Pythonic way:
if 18 <= age <= 65:
print("Working age adult")

and, or, and not allow you to build complex decision trees.

Python is efficient. It stops evaluating an expression as soon as the result is certain.

  1. A and B: If A is False, Python returns A and does not even look at B.
  2. A or B: If A is True, Python returns A and does not even look at B.
short_circuit_logic.py
def log_and_return():
print("This ran!")
return True
# Since the first part is False, the function NEVER runs.
result = False and log_and_return()

Bitwise operators treat integers as strings of binary 0s and 1s. These are primarily used in low-level systems programming, cryptography, and performance optimization.

OperatorNameActionExample (5 is 0101, 3 is 0011)
&AND1 if both bits are 1.5 & 3 -> 0001 (1)
``OR1 if either bit is 1.
^XOR1 if bits are different.5 ^ 3 -> 0110 (6)
~NOTInverts all bits.~5 -> -6 (due to 2’s complement)
<<L-ShiftMoves bits left (multiplies by 2).5 << 1 -> 1010 (10)
>>R-ShiftMoves bits right (divides by 2).5 >> 1 -> 0010 (2)

When you mix operators, Python follows a strict hierarchy (order of operations).

  1. Parentheses () (Always use these to be explicit!)
  2. Exponentiation **
  3. Multiplication/Division *, /, //, %
  4. Addition/Subtraction +, -
  5. Comparisons ==, >, <, etc.
  6. Logical not
  7. Logical and
  8. Logical or
# Is it (10 + 2) * 5 or 10 + (2 * 5)?
result = 10 + 2 * 5
# Multiplication is higher: 10 + 10 = 20