Tutorials Python Python Numbers & Math
Ch 9 / 58
Python Beginner 9 min read Chapter 9 of 58

Python Numbers & Math

Numbers are the foundation of every program — from counting loop iterations to powering machine learning models. Python has three built-in numeric types (int, float, complex), a rich set of arithmetic operators, and a powerful math module. This chapter covers all of them with practical, runnable examples.

What you'll learn in this chapter
Python's three numeric types: int, float, complex
All arithmetic operators with precedence rules
Type conversion: int(), float(), complex()
Built-in numeric functions: abs(), round(), pow()
The math module: sqrt, log, trig & constants
Number formatting, random numbers & real-world examples
Advertisement

Python Number Types

Python has three built-in numeric types. Unlike many languages you never need to declare which type you want — Python infers it from the literal value you assign. All three types are objects, meaning they have methods you can call on them.

Key fact Python integers have unlimited precision — they grow as large as your RAM allows. There is no integer overflow in pure Python.
int
Whole numbers, any size
float
Decimal / fractional numbers
complex
Real + imaginary parts
Unlimited int
No overflow — ever
Python — number_types.py
# int — whole numbers (positive, negative, zero)
x = 42
y = -7
big = 999_999_999_999_999_999   # underscores for readability

# float — decimal numbers (IEEE 754 double precision)
pi    = 3.14159
temp  = -0.5
sci   = 1.5e10               # 1.5 × 10¹⁰ — scientific notation
tiny  = 2.7e-4               # 0.00027

# complex — real + imaginary (j notation)
c1 = 3 + 4j
c2 = complex(2, -5)         # 2-5j

# Check types
print(type(x))    # <class 'int'>
print(type(pi))   # <class 'float'>
print(type(c1))   # <class 'complex'>

Integers (int)

Python integers are arbitrary precision — they can be as large as available memory. You can write integer literals in decimal, binary (0b), octal (0o), and hexadecimal (0x) notation. Use underscores to separate digit groups for readability.

Python — integers.py
# Decimal (base 10) — default
a = 1_000_000          # same as 1000000

# Binary (base 2) — prefix 0b
b = 0b1010              # = 10 in decimal
print(bin(255))         # '0b11111111'

# Octal (base 8) — prefix 0o
o = 0o17               # = 15 in decimal
print(oct(64))          # '0o100'

# Hexadecimal (base 16) — prefix 0x
h = 0xFF               # = 255 in decimal
print(hex(255))         # '0xff'

# Unlimited precision — no overflow!
huge = 2 ** 100
print(huge)
# 1267650600228229401496703205376

# int is immutable and hashable — safe as dict key
d = {1: "one", 2: "two"}
print(d[1])             # one
bin(n)
Returns a string with the binary representation of n, prefixed with 0b.
oct(n)
Returns a string with the octal representation of n, prefixed with 0o.
hex(n)
Returns a string with the hexadecimal representation of n, prefixed with 0x.
2 ** 100
Python computes this exactly — no overflow, no approximation. Java and C would silently wrap or throw an error.

Floating-Point Numbers (float)

Floats store decimal and fractional numbers using the IEEE 754 double-precision standard — the same used in JavaScript, Java, and C's double. This gives about 15–17 significant digits of precision.

Python — floats.py
x = 3.14
y = 1.0               # trailing .0 makes it a float
z = 2.5e3             # 2500.0 — scientific notation

print(type(y))        # <class 'float'>

# Floating-point precision quirk
print(0.1 + 0.2)      # 0.30000000000000004  ← IEEE 754 artefact
print(round(0.1 + 0.2, 2))  # 0.3  ← use round() for display

# Special float values
inf  = float('inf')  # positive infinity
ninf = float('-inf') # negative infinity
nan  = float('nan')  # Not a Number

print(1 / 0.0)          # raises ZeroDivisionError
print(inf + 1)          # inf
print(inf - inf)        # nan

# Check for special values
import math
print(math.isinf(inf))  # True
print(math.isnan(nan))  # True
print(math.isfinite(3.14)) # True
Float precision warning Never compare floats with ==. Use math.isclose(a, b) or round() instead. 0.1 + 0.2 == 0.3 returns False in Python — and every other language using IEEE 754.

Complex Numbers (complex)

Python has native support for complex numbers — no library needed. A complex number is written as real + imagj where j (not i) denotes the imaginary unit. They are used in signal processing, electrical engineering, and scientific computing.

Python — complex_numbers.py
c1 = 3 + 4j
c2 = complex(1, -2)   # 1-2j

# Access parts
print(c1.real)         # 3.0
print(c1.imag)         # 4.0
print(c1.conjugate())  # (3-4j)

# Arithmetic on complex numbers
print(c1 + c2)         # (4+2j)
print(c1 * c2)         # (11+2j)  — (3+4j)(1-2j)
print(abs(c1))         # 5.0  — magnitude √(3²+4²)

# cmath module for complex math functions
import cmath
print(cmath.phase(c1))  # 0.9272... radians (angle)
print(cmath.polar(c1))  # (5.0, 0.9272...)  — (r, θ)
print(cmath.sqrt(-1))   # 1j  — √(-1) = i
Advertisement
K2infocom Python Masterclass & Backend Development
Master Python, Django & Backend APIs with AI
Go from absolute beginner to building production-ready REST APIs, web applications, and ML pipelines. Real projects, live mentoring in Vadodara, and placement support included.
2,400+
Students Enrolled
4.9 ⭐
Google Rating
6 Months
Full Program
100%
Placement Support
Python 3 Django & DRF FastAPI PostgreSQL Machine Learning Docker & AWS Real Projects AI Tools

Arithmetic Operators & Precedence

Python supports seven arithmetic operators. Understanding operator precedence (the order Python evaluates them) is critical to writing correct expressions. Use parentheses to override precedence whenever clarity matters.

Python — arithmetic.py
a, b = 17, 5

print(f"Addition:        {a} + {b}  = {a + b}")    # 22
print(f"Subtraction:     {a} - {b}  = {a - b}")    # 12
print(f"Multiplication:  {a} * {b}  = {a * b}")    # 85
print(f"True Division:   {a} / {b}  = {a / b}")    # 3.4   (always float)
print(f"Floor Division:  {a} // {b} = {a // b}")   # 3     (truncates)
print(f"Modulus:         {a} % {b}  = {a % b}")    # 2     (remainder)
print(f"Exponentiation:  {a} ** {b} = {a ** b}")   # 1419857

# Operator precedence (high → low):
# 1. ()  parentheses
# 2. **  exponentiation (right-to-left)
# 3. +x, -x, ~x  unary
# 4. *, /, //, %  multiplication family
# 5. +, -  addition & subtraction

print(2 + 3 * 4)        # 14  — * before +
print((2 + 3) * 4)      # 20  — () first
print(2 ** 3 ** 2)      # 512 — ** right-to-left: 2**(3**2)=2**9

# Augmented assignment operators
n = 10
n += 5    # n = n + 5  → 15
n -= 3    # n = n - 3  → 12
n *= 2    # n = n * 2  → 24
n //= 5   # n = n // 5 → 4
n **= 3   # n = n ** 3 → 64
print(n)               # 64
Operator Name Example Result Notes
+ Addition 7 + 3 10 Works on int, float, complex
- Subtraction 7 - 3 4 Works on int, float, complex
* Multiplication 7 * 3 21 Also repeats strings/lists
/ True Division 7 / 2 3.5 Always returns float in Python 3
// Floor Division 7 // 2 3 Rounds down toward −∞
% Modulus 7 % 3 1 Remainder; odd/even check
** Exponentiation 2 ** 10 1024 Right-to-left associativity
Modulus trick n % 2 == 0 checks if n is even; n % 2 == 1 checks if it's odd. n % 10 gives the last digit of n.

Type Conversion

Python is strongly typed — it does not silently mix incompatible types. You must explicitly convert between types using the built-in functions int(), float(), and complex(). Python also automatically promotes types in mixed-type expressions.

Python — type_conversion.py
# Explicit conversion
print(int(3.9))          # 3    — truncates, does NOT round
print(int(-3.9))         # -3   — truncates toward zero
print(int("42"))          # 42   — string → int
print(int("0xFF", 16))   # 255  — hex string → int
print(int("1010", 2))    # 10   — binary string → int

print(float(7))           # 7.0  — int → float
print(float("3.14"))      # 3.14 — string → float
print(float("inf"))       # inf

print(complex(4))         # (4+0j)
print(complex(2, 3))     # (2+3j)

# Implicit promotion in mixed expressions
print(type(3 + 2.0))    # float — int + float → float
print(type(3 + 2j))     # complex — int + complex → complex
print(type(1.0 + 2j))   # complex — float + complex → complex

# Common mistake: int() truncates, not rounds!
print(int(2.9))   # 2 — use round(2.9) → 3 if you want rounding
Promotion hierarchy Python auto-promotes numeric types: int → float → complex. Whenever you mix types in an expression, the result is promoted to the "wider" type automatically.

Built-in Functions & the Math Module

Python provides several built-in numeric functions available without any import. For advanced mathematics, import math gives you trigonometry, logarithms, constants, and more. For random numbers, use the random module.

Built-in Numeric Functions

Python — builtin_functions.py
# abs() — absolute value
print(abs(-7))          # 7
print(abs(-3.5))        # 3.5
print(abs(3 + 4j))      # 5.0  — magnitude of complex

# round() — rounds to n decimal places
print(round(3.14159, 2)) # 3.14
print(round(2.5))        # 2   — banker's rounding (round half to even)
print(round(3.5))        # 4

# pow() — exponentiation (3rd arg = modulo)
print(pow(2, 10))        # 1024  — same as 2**10
print(pow(2, 10, 1000))  # 24    — (2**10) % 1000

# divmod() — (quotient, remainder) together
print(divmod(17, 5))    # (3, 2)  — 17 = 3×5 + 2

# min(), max(), sum()
nums = [4, 1, 9, 2, 7]
print(min(nums))         # 1
print(max(nums))         # 9
print(sum(nums))         # 23

The math Module

Python — math_module.py
import math

# Constants
print(math.pi)          # 3.141592653589793
print(math.e)           # 2.718281828459045
print(math.tau)         # 6.283185307179586  (2π)
print(math.inf)         # inf

# Rounding & sign
print(math.floor(3.9))  # 3   — round down
print(math.ceil(3.1))   # 4   — round up
print(math.trunc(3.9)) # 3   — toward zero
print(math.fabs(-4.5)) # 4.5 — float absolute value

# Power & logarithms
print(math.sqrt(144))  # 12.0
print(math.isqrt(17)) # 4    — integer square root
print(math.pow(2, 8))  # 256.0 — returns float
print(math.log(100, 10)) # 2.0  — log base 10
print(math.log2(1024)) # 10.0 — log base 2
print(math.log10(1000))# 3.0  — log base 10
print(math.exp(1))     # 2.718...  e¹

# Trigonometry (all angles in radians)
print(math.sin(math.pi / 2))  # 1.0
print(math.cos(0))             # 1.0
print(math.tan(math.pi / 4))  # 1.0
print(math.degrees(math.pi))  # 180.0 — rad → deg
print(math.radians(90))       # 1.5707... — deg → rad

# Factorial & combinatorics
print(math.factorial(6))  # 720
print(math.gcd(48, 18))   # 6   — greatest common divisor
print(math.lcm(4, 6))     # 12  — least common multiple (Python 3.9+)
print(math.comb(5, 2))    # 10  — C(5,2) combinations
print(math.perm(5, 2))    # 20  — P(5,2) permutations

Random Numbers

Python — random_module.py
import random

# Float in [0.0, 1.0)
print(random.random())           # e.g. 0.7312

# Float in [a, b]
print(random.uniform(1.5, 9.5))  # e.g. 5.234

# Integer in [a, b] inclusive
print(random.randint(1, 6))      # dice roll: 1–6

# Random choice from a sequence
colours = ["red", "green", "blue"]
print(random.choice(colours))    # e.g. "green"

# Shuffle a list in place
deck = [1, 2, 3, 4, 5]
random.shuffle(deck)
print(deck)                       # e.g. [3, 1, 5, 2, 4]

# Reproducible randomness — set a seed
random.seed(42)
print(random.randint(1, 100))   # always 82 with seed 42
math.floor(x)
Rounds down to the nearest integer — always toward −∞. math.floor(-3.1) → -4.
math.ceil(x)
Rounds up to the nearest integer — always toward +∞. math.ceil(-3.9) → -3.
math.gcd(a, b)
Greatest common divisor — useful for simplifying fractions: math.gcd(48, 18) → 6.
random.seed(n)
Sets the random generator's seed so results are reproducible — essential for testing and machine learning experiments.

Practice Python Online — Free Compilers

Try all the number and math examples from this chapter directly in your browser. No installation needed — pick any free Python environment below.

▶
Online Python 3 Compiler
Write, run and debug Python code in your browser. No installation required. Supports the math and random modules.
Open Compiler
Replit
Full IDE online
Google Colab
Free GPU notebooks
JupyterLite
Notebooks in browser
Programiz
Beginner-friendly
Chapter Summary
  • Python has three numeric types: int (unlimited precision), float (IEEE 754 double), and complex (real + imaginary).
  • Integer literals can be written in decimal, binary (0b), octal (0o), or hex (0x). Use _ as a digit separator.
  • The 7 arithmetic operators: +, -, *, /, //, %, **. Division (/) always returns a float.
  • Never compare floats with == — use math.isclose() or round() to handle IEEE 754 imprecision.
  • Use int(), float(), complex() for explicit conversion. Python promotes automatically in mixed-type expressions.
  • math module: sqrt, floor, ceil, log, sin/cos/tan, factorial, gcd — import once and use freely.
  • Use random.seed(n) for reproducible results in simulations and machine learning experiments.
  • Key built-ins: abs(), round(), pow(), divmod(), min(), max(), sum() — no import needed.
⚡
Free Resource
Download our Python Numbers & Math Cheat Sheet
All operators, math module functions, random module and type conversion — one printable page.
Get Sheet
Advertisement
Quick Check — Test Your Understanding
Question & Answer
✓ Answer

The / operator performs true division and always returns a float, even when dividing two integers: 10 / 2 → 5.0. The // operator performs floor division — it divides and then rounds down toward negative infinity, returning an integer when both operands are integers: 10 // 3 → 3, and -7 // 2 → -4 (not -3 — it rounds toward −∞). This is a key difference from Python 2, where / on two integers performed floor division.

✓ Answer

Python's float type uses the IEEE 754 double-precision binary format. Most decimal fractions (like 0.1 and 0.2) cannot be represented exactly in binary — just as 1/3 cannot be represented exactly in decimal. The stored binary values are the closest representable approximations, and when added, their combined rounding error makes the result 0.30000000000000004 instead of 0.3. This is not a Python bug — it affects every language using IEEE 754 (Java, JavaScript, C, etc.). The fix: use round(0.1 + 0.2, 2) for display, or math.isclose(a, b) for comparisons, or the decimal module for exact arithmetic.

✓ Answer

int() truncates (cuts off) the decimal part — it does not round. It always moves toward zero: int(3.9) → 3 and int(-3.9) → -3. To round to the nearest integer, use the built-in round() function instead: round(3.9) → 4. For always rounding down use math.floor(), and for always rounding up use math.ceil().

✓ Answer

Use the modulus operator %. n % 2 == 0 is True if n is even (divisible by 2 with no remainder), and n % 2 != 0 (or n % 2 == 1) is True if n is odd. Example:

n = 17
if n % 2 == 0:
    print("even")
else:
    print("odd")   # → odd
✓ Answer
  • math.floor(x) — rounds down toward −∞. floor(-2.3) → -3.
  • math.ceil(x) — rounds up toward +∞. ceil(-2.3) → -2.
  • math.trunc(x) — rounds toward zero (same as int()). trunc(-2.9) → -2.
  • round(x, n) — rounds to n decimal places using banker's rounding (half rounds to even): round(2.5) → 2, round(3.5) → 4.
MCQ 1 of 3
What is the result of 17 % 5 in Python?
MCQ 2 of 3
What does type(3 + 2.0) return in Python?
MCQ 3 of 3
Which function returns the largest integer ≤ x (rounds toward −∞)?

Rate Us on Google

4.8 / 5
Enjoying this tutorial?
Your 5-star review helps other learners discover our free tutorials and encourages us to keep creating quality content.
80+ reviews
Write a Google Review
Join WhatsApp Channel