Python Numbers & Math
Python has three number types and a rich set of tools for working with them. This lesson covers arithmetic, rounding, the float precision trap, the math module and random numbers.
- int, float and complex numbers
- Arithmetic including // and %
- Rounding and float precision
- The math and random modules
Three number types
count = 42 # int: whole number, any sizeratio = 0.75 # float: decimal numbersignal = 3 + 4j # complex: real + imaginary part print(type(count).__name__, type(ratio).__name__, type(signal).__name__)print(abs(signal)) # length of the complex numberint float complex 5.0
Large numbers are easier to read with underscores. Python ignores them:
population = 1_428_627_663print(population)print(2 ** 64)1428627663 18446744073709551616
Arithmetic operators
| Operator | Meaning | 17 ? 5 |
|---|---|---|
+ | add | 22 |
- | subtract | 12 |
* | multiply | 85 |
/ | divide (always float) | 3.4 |
// | floor divide (round down) | 3 |
% | remainder (modulo) | 2 |
** | power | 1419857 |
a, b = 17, 5print(a + b, a - b, a * b)print(a / b, a // b, a % b)print(a ** b)22 12 85 3.4 3 2 1419857
// and % work as a pair: a == (a // b) * b + a % b. divmod() gives both at once. A classic use is converting seconds:
seconds = 3725minutes, secs = divmod(seconds, 60)hours, minutes = divmod(minutes, 60)print(f"{hours}h {minutes}m {secs}s")1h 2m 5s
n % 2 == 0 is the standard test for an even number. Many practice programs use it.
Order of operations
Python follows the usual maths rules: * first, then , /, //, %, then + and -. Use parentheses to make your intent clear.
print(2 + 3 * 4)print((2 + 3) * 4)print(2 ** 3 ** 2) # ** groups from the right: 2 ** 9print(-2 ** 2) # ** binds tighter than the minus sign14 20 512 -4
Rounding
price = 2.675print(round(price, 2))print(round(2.5), round(3.5)) # ties round to the even numberprint(int(7.9), int(-7.9)) # int() cuts off the decimals2.67 2 4 7 -7
round(2.5) gives 2 because Python uses “banker’s rounding”: a tie goes to the nearest even number. round(2.675, 2) gives 2.67 because 2.675 cannot be stored exactly as a float; it is really slightly less.
Float precision
print(0.1 + 0.2)print(0.1 + 0.2 == 0.3) import mathprint(math.isclose(0.1 + 0.2, 0.3))0.30000000000000004 False True
For money, use Decimal with string inputs, which stores decimal digits exactly:
from decimal import Decimal print(Decimal("0.1") + Decimal("0.2"))total = Decimal("19.99") * 3print(total)0.3 59.97
Never compare floats with ==. Use math.isclose() or compare rounded values.
Useful built-in functions
nums = [4, -9, 15, 2]print(abs(-9), max(nums), min(nums), sum(nums))print(pow(2, 10), pow(2, 10, 1000)) # third argument: remainder9 15 -9 12 1024 24
The math module
import math print(math.sqrt(144))print(math.floor(4.7), math.ceil(4.2))print(math.pi)print(math.factorial(5))print(math.gcd(48, 36), math.lcm(4, 6))print(round(math.log10(1000)), round(math.hypot(3, 4)))12.0 4 5 3.141592653589793 120 12 12 3 5
Random numbers
The random module picks pseudo-random values. random.seed() makes the sequence repeatable, which is useful in tests.
import random random.seed(7)print(random.randint(1, 6)) # dice roll: 1 to 6 inclusiveprint(random.choice(["red", "green", "blue"]))print(round(random.random(), 3)) # float from 0.0 up to 1.03 red 0.395
Number systems
print(bin(10), oct(10), hex(255))print(int("1010", 2), int("ff", 16))0b1010 0o12 0xff 10 255
Check your understanding
Predict the output
print(7 // 2, -7 // 2, 7 % 3, -7 % 3)3 -4 1 2
// rounds down, towards negative infinity, so -7 // 2 is -4, not -3. The remainder takes the sign of the divisor, so -7 % 3 is 2.
Quick quiz
1. What does 10 / 2 return?
/ always returns a float in Python 3.
2. What does round(2.5) return?
Ties round to the nearest even number, so 2.5 becomes 2 and 3.5 becomes 4.
3. How do you get the remainder of 17 divided by 5?
% is the modulo (remainder) operator; 17 % 5 is 2.
4. Which is the safe way to compare two floats?
Floats are approximate, so compare them with a tolerance.
Exercise: simple interest
Calculate simple interest and the total amount, rounded to 2 decimals.
principal = 15000, rate = 7.5 (% per year), years = 3
Interest: 3375.0 Total: 18375.0
Hint 1
Simple interest is principal * rate * years / 100.
principal = 15000rate = 7.5years = 3 interest = principal * rate * years / 100print("Interest:", round(interest, 2))print("Total:", round(principal + interest, 2))Interest: 3375.0 Total: 18375.0
The formula is applied directly. round(x, 2) keeps two decimals for display; here the result is exact, so it prints 3375.0.
Program Practice
40 Python Basic Programs
Every program has a step-by-step explanation, colour-coded code and its real output.
Python numbers and math FAQ
What is the difference between / and // in Python?
/ is true division and always returns a float (7 / 2 is 3.5). // is floor division and rounds down (7 // 2 is 3).
Why does 0.1 + 0.2 not equal 0.3 in Python?
Floats are stored in binary, which cannot represent 0.1 exactly. The result is 0.30000000000000004. Use math.isclose() or decimal.Decimal when exactness matters.
How do I round a number to 2 decimal places in Python?
Use round(x, 2) to get a number, or f"{x:.2f}" to get a string for display.
How do I get the square root in Python?
Use math.sqrt(x) after import math, or x ** 0.5.