Python Tutorial › Basics › Numbers & Math

Python Numbers & Math

BeginnerLesson 10 of 4711 min read12 runnable examples

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.

Advertisement
In this lesson
  • int, float and complex numbers
  • Arithmetic including // and %
  • Rounding and float precision
  • The math and random modules

Three number types

Python
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 number
Output
int float complex
5.0

Large numbers are easier to read with underscores. Python ignores them:

Python
population = 1_428_627_663print(population)print(2 ** 64)
Output
1428627663
18446744073709551616

Arithmetic operators

OperatorMeaning17 ? 5
+add22
-subtract12
*multiply85
/divide (always float)3.4
//floor divide (round down)3
%remainder (modulo)2
**power1419857
Python
a, b = 17, 5print(a + b, a - b, a * b)print(a / b, a // b, a % b)print(a ** b)
Output
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:

Python
seconds = 3725minutes, secs = divmod(seconds, 60)hours, minutes = divmod(minutes, 60)print(f"{hours}h {minutes}m {secs}s")
Output
1h 2m 5s
Tip

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.

Python
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 sign
Output
14
20
512
-4

Rounding

Python
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 decimals
Output
2.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

Python
print(0.1 + 0.2)print(0.1 + 0.2 == 0.3) import mathprint(math.isclose(0.1 + 0.2, 0.3))
Output
0.30000000000000004
False
True

For money, use Decimal with string inputs, which stores decimal digits exactly:

Python
from decimal import Decimal print(Decimal("0.1") + Decimal("0.2"))total = Decimal("19.99") * 3print(total)
Output
0.3
59.97
Watch out

Never compare floats with ==. Use math.isclose() or compare rounded values.

Useful built-in functions

Python
nums = [4, -9, 15, 2]print(abs(-9), max(nums), min(nums), sum(nums))print(pow(2, 10), pow(2, 10, 1000))   # third argument: remainder
Output
9 15 -9 12
1024 24

The math module

Python
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)))
Output
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.

Python
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.0
Output
3
red
0.395

Number systems

Python
print(bin(10), oct(10), hex(255))print(int("1010", 2), int("ff", 16))
Output
0b1010 0o12 0xff
10 255

Check your understanding

Predict the output

print(7 // 2, -7 // 2, 7 % 3, -7 % 3)

Quick quiz

1. What does 10 / 2 return?

2. What does round(2.5) return?

3. How do you get the remainder of 17 divided by 5?

4. Which is the safe way to compare two floats?

Exercise: simple interest

Calculate simple interest and the total amount, rounded to 2 decimals.

Input
principal = 15000, rate = 7.5 (% per year), years = 3
Expected output
Interest: 3375.0
Total: 18375.0
Hint 1

Simple interest is principal * rate * years / 100.

Program Practice

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.

Leave a Comment