Reading — step 1 of 8
Learn
Python is a surprisingly powerful calculator. You can open a Python prompt and start doing math immediately — no imports, no setup, no ceremony. But there's more to numbers in Python than addition and subtraction. Understanding how Python handles arithmetic will save you from subtle bugs that haunt beginners for weeks.
The seven arithmetic operators
Three of those deserve careful attention.
/ vs // — the two divisions
Python has TWO division operators, and confusing them is a classic beginner bug.
/is true division. It always returns afloat, even when the result is whole:10 / 2is5.0, not5.//is floor division. It rounds down toward negative infinity and returns the same type as its inputs:10 // 2is5,7 // 2is3,-7 // 2is-4(NOT-3).
Use / when you want a precise mathematical result. Use // when you want a whole-number result — for example, splitting items into groups.
% — the modulo (remainder) operator
% returns what's left over after a floor division. 17 % 5 is 2 because 17 = 3 × 5 + 2. The remainder operator unlocks several patterns you'll use constantly:
Order of operations (PEMDAS)
Python follows standard math order of operations:
- Parentheses
- Exponents (
**) - Multiplication, Division, floor division, modulo (left to right)
- Addition, Subtraction (left to right)
When unsure, add parentheses. They never hurt readability — the opposite, in fact.
Float precision — the surprising bug
Floating-point numbers can't represent every decimal exactly. The number 0.1 in binary is a repeating fraction, just like 1/3 is in decimal.
This is not a Python quirk; it's how IEEE 754 floats work in every language. Never compare floats with == directly. Instead, check whether they're "close enough":
For money, use the decimal module instead of float — Decimal('0.1') + Decimal('0.2') is exactly Decimal('0.3').
Python ints have no overflow
In languages like C or Java, integers have a maximum size and "wrap around" or overflow. Python ints have no maximum:
This is amazing for math-heavy code and one of Python's quietly great features.
Useful built-in math functions
A handful of functions are always available without imports:
For more (sqrt, log, trig, constants), import math and use math.sqrt(2), math.pi, etc.
Common mistakes
- Using
/when you wanted//. Half your numbers come out as5.0instead of5. Looks weird, sometimes causes downstream type bugs. - Comparing floats with
==. Usemath.isclose()or work with thedecimalmodule. - Forgetting parentheses in long expressions.
1 / 2 + 3is3.5, not0.2.
Discussion
Ask a question, share an insight, or help someone who’s stuck.
Sign in to post a comment or reply.
Loading…