Numbers and Math in Python
A practical guide to integers, floats, arithmetic operators, operator precedence, the math module, and the floating-point gotchas every Python beginner should know.
What you'll learn
- ✓How Python handles integers and floats
- ✓All seven arithmetic operators, including integer division and modulo
- ✓Operator precedence and how to use parentheses for clarity
- ✓Useful built-in functions: abs, round, min, max, pow, sum
- ✓The math module for advanced operations
- ✓Floating-point precision and how to handle money
Prerequisites
- •Familiarity with Python data types — see Data Types
Most programs do math at some point — totals, counts, percentages, scores, prices. Python’s number support is straightforward, but it has a few quirks worth understanding now so they do not surprise you later.
Integers and floats
Python has two main numeric types.
count = 42 # int — a whole number
price = 19.99 # float — a number with a fractional part
Integers in Python have no fixed maximum size. Unlike many languages, you can compute with arbitrarily large integers and Python will simply use more memory:
print(2 ** 200)
# 1606938044258990275541962092341162602522202993782792835301376
Floats follow the IEEE 754 double-precision standard, the same as JavaScript and most other languages. They are fast but, as we’ll see at the end, not exact for every decimal.
You can convert between the two with int() and float():
print(int(3.9)) # 3 — truncates, does not round
print(float(5)) # 5.0
int() always truncates toward zero. If you want rounding, use the round() function below.
The seven arithmetic operators
Python supports the operators you would expect, plus two that often surprise newcomers.
| Operator | Name | Example | Result |
|---|---|---|---|
+ | Addition | 7 + 3 | 10 |
- | Subtraction | 7 - 3 | 4 |
* | Multiplication | 7 * 3 | 21 |
/ | Division | 7 / 3 | 2.333... |
// | Integer division | 7 // 3 | 2 |
% | Modulo (remainder) | 7 % 3 | 1 |
** | Exponent (power) | 7 ** 3 | 343 |
A complete demo in the REPL:
>>> 10 + 4
14
>>> 10 - 4
6
>>> 10 * 4
40
>>> 10 / 4
2.5
>>> 10 // 4
2
>>> 10 % 4
2
>>> 10 ** 4
10000
Division: / always returns a float
In Python 3 the / operator always returns a float, even if both operands are integers:
print(10 / 2) # 5.0
print(type(10 / 2)) # <class 'float'>
If you need an integer result, use // (integer division), which discards the fractional part:
print(10 // 3) # 3
print(11 // 3) # 3
print(-7 // 2) # -4 (rounds toward negative infinity)
Modulo: the remainder
The % operator returns the remainder of a division. It is enormously useful — for paginating, alternating, checking even/odd, and many other patterns:
print(10 % 3) # 1
print(14 % 7) # 0 — 14 is exactly divisible by 7
print(15 % 2) # 1 — odd
print(8 % 2) # 0 — even
Exponent: **
** raises the left operand to the power of the right operand:
print(2 ** 10) # 1024
print(9 ** 0.5) # 3.0 — square root
Operator precedence
When multiple operators appear in one expression, Python applies them in a defined order — roughly the order from your school maths classes:
- Parentheses
(...) - Exponentiation
** - Unary minus
-x - Multiplication, division, modulo
* / // % - Addition, subtraction
+ -
print(2 + 3 * 4) # 14 — multiplication first
print((2 + 3) * 4) # 20 — parentheses force order
print(2 ** 3 ** 2) # 512 — right-associative: 2 ** (3 ** 2)
The rule for keeping readers (and future you) sane is simple: when in doubt, use parentheses. They cost nothing and remove ambiguity.
Useful built-in number functions
Python provides several number-related functions that don’t require importing anything.
print(abs(-7)) # 7 — absolute value
print(round(3.7)) # 4
print(round(3.14159, 2)) # 3.14 — round to N decimal places
print(min(5, 2, 8)) # 2
print(max(5, 2, 8)) # 8
print(pow(2, 10)) # 1024 — same as 2 ** 10
print(sum([1, 2, 3, 4])) # 10 — total of an iterable
A subtle but useful behaviour of round(): it uses banker’s rounding (round-half-to-even):
print(round(0.5)) # 0
print(round(1.5)) # 2
print(round(2.5)) # 2
This avoids a small statistical bias when rounding many numbers, but can surprise you the first time you see it.
The math module
For anything beyond basic arithmetic, the standard math module is the answer.
import math
print(math.pi) # 3.141592653589793
print(math.e) # 2.718281828459045
print(math.sqrt(16)) # 4.0
print(math.floor(3.7)) # 3 — round down
print(math.ceil(3.2)) # 4 — round up
print(math.log(100, 10)) # 2.0 — log base 10
print(math.log(math.e)) # 1.0 — natural log
print(math.factorial(5)) # 120
For trigonometry, the module provides sin, cos, tan, and their inverses — all of which work in radians, not degrees. math.radians() and math.degrees() convert between the two.
Try it yourself. Calculate the area of a circle with radius 7 using math.pi. Then calculate the hypotenuse of a right triangle with sides 3 and 4 using math.sqrt. Confirm you get 153.93... and 5.0 respectively.
Formatting numbers for display
When you want a number to appear in a specific format — fixed decimal places, thousands separators, percentages — use f-strings:
price = 1234.5678
print(f"Total: ${price:.2f}") # Total: $1234.57
print(f"Total: ${price:,.2f}") # Total: $1,234.57
ratio = 0.875
print(f"Score: {ratio:.1%}") # Score: 87.5%
The : inside the braces introduces a format specifier. .2f means “fixed-point, two decimal places.” ,.2f adds a thousands separator. .1% displays the value as a percentage with one decimal place.
We’ll cover f-strings in much more depth in the post on strings.
The floating-point gotcha
This is the most famous quirk in Python, and in nearly every other mainstream language:
print(0.1 + 0.2) # 0.30000000000000004
print(0.1 + 0.2 == 0.3) # False
This is not a Python bug. It is a property of the binary floating-point representation used by virtually every computer on Earth. Some decimals cannot be represented exactly in binary, the same way 1/3 cannot be written exactly in decimal.
For most calculations this is invisible and irrelevant. For two cases it matters:
1. Comparing floats for equality. Don’t:
# Don't
if a == b:
...
# Do
if math.isclose(a, b):
...
2. Money. Floats are the wrong tool for currency. Use the decimal module:
from decimal import Decimal
total = Decimal("0.1") + Decimal("0.2")
print(total) # 0.3 — exactly
Pass numbers as strings to Decimal, not floats — passing a float defeats the purpose because the float is already imprecise.
Try it yourself. Use math.isclose() to compare 0.1 + 0.2 with 0.3 and confirm it returns True. Then build a small price calculator using Decimal for two prices and confirm the result is exact.
Recap
You now know:
- Python provides
int(unlimited size) andfloat(IEEE 754) for numbers - The seven arithmetic operators:
+ - * / // % ** - Operator precedence follows familiar maths rules — parentheses remove ambiguity
- Built-in functions cover the everyday cases:
abs,round,min,max,pow,sum - The
mathmodule covers everything else — square roots, logs, trig, constants - f-strings format numbers for display
- Floats are imprecise by nature — use
math.isclosefor comparison andDecimalfor money
Next steps
The next post is a deep dive into strings — Python’s most heavily used type. We’ll cover creation, escaping, indexing, slicing, the most important methods, and f-strings in depth.
→ Next: Strings in Python: Everything a Beginner Needs
Questions or feedback? Email codeloomdevv@gmail.com.