Topic 35 of 64
Arithmetic Operators
Overview
Python's arithmetic operators include standard math plus floor division (//) and exponentiation (**). Knowing their precedence and behavior with integers vs floats prevents common calculation errors.
Syntax
python
a, b = 10, 3
a + b # 13 — addition
a - b # 7 — subtraction
a * b # 30 — multiplication
a / b # 3.333... — true division (always float)
a // b # 3 — floor division
a % b # 1 — modulo (remainder)
a ** b # 1000 — exponentiation
# Augmented assignment
x = 5
x += 3 # x = 8
x **= 2 # x = 64Common Pitfalls
- Python ** has higher precedence than unary minus: -2**2 evaluates as -(2**2) = -4, not (-2)**2 = 4.
- Floor division // always rounds toward negative infinity: -7 // 2 = -4, not -3.
- Interview tip: Know the PEMDAS/BODMAS operator precedence — ** > unary - > *, /, //, % > +, -.
Real-World Example
Pagination logic using floor division and modulo
example
python
def pagination_info(total_items: int, page_size: int) -> dict:
total_pages = (total_items + page_size - 1) // page_size
# Equivalent to: math.ceil(total_items / page_size)
return {
"total_items": total_items,
"page_size": page_size,
"total_pages": total_pages,
}
print(pagination_info(101, 10)) # {'total_pages': 11}