Python Numbers
Integers, Floats, Complex & Math
Master every numeric type in Python: integers, floating-point numbers, complex numbers, arithmetic operations, the math module, random number generation, Decimal, Fraction, and formatting. 24 interactive lessons with runnable code โ crafted by @PoeticGlenn.
What you will learn
Everything about numbers in Python โ from the humble integer to complex numbers, from basic arithmetic to advanced math functions, random generation, and precise decimal arithmetic. Each concept is broken down step-by-step with interactive code examples from @PoeticGlenn.
Why Numbers Are the Foundation of Programming
Numbers are everywhere in programming. From counting loops and calculating statistics to
building financial systems and scientific simulations, understanding how Python handles
numbers is essential. This curriculum, designed by @PoeticGlenn,
covers integers, floats, complex numbers, arithmetic, the math module, random
numbers, and the precision tools Decimal and Fraction โ everything
you need to work with numeric data confidently.
All Number Types
Integers, floats, complex numbers โ learn when to use each and how they work under the hood.
Advanced Math
From trigonometry to logarithms, the math module gives you the full power of mathematical computing.
Randomness & Precision
Generate random numbers for games and simulations, and use Decimal for exact financial calculations.
"The best way to predict the future is to implement it." โ Numbers make that possible. ๐
Numeric Mastery Unlocks Every Domain
Whether you're building a game, analyzing financial data, simulating physics, or training a machine learning model, you need to be fluent in Python's numeric capabilities. This curriculum, curated by @PoeticGlenn, gives you the confidence to tackle any numeric challenge.
๐ Data Science & AI
NumPy, pandas, and scikit-learn all rely on Python's numeric types and the math module.
๐ฐ Finance & Accounting
Use Decimal for exact currency calculations, avoiding floating-point rounding errors.
๐ฎ Game Development
Random numbers drive game mechanics, physics, and procedural generation.
๐ฌ Science & Engineering
Complex numbers, trigonometry, and logarithms are essential for scientific computing.
Why Numeric Computing Drives Innovation
From the earliest computers to the latest AI models, numbers have been at the heart of computing. Python's numeric types and libraries are used by scientists, engineers, and developers around the world to solve real problems. This curriculum, designed by @PoeticGlenn, gives you the tools to join them.
Data Analysis
Python is the #1 language for data analysis, and numbers are the raw material.
Scientific Computing
From physics simulations to genetic algorithms, Python is used in cutting-edge research.
FinTech
Algorithmic trading, risk analysis, and banking systems rely on precise numeric computation.
The numbers you work with today may change the world tomorrow.
๐ Table of Contents
Jump to any section โ all entries are equal size
๐ข Integers โ Whole Numbers
Integers are whole numbers without a decimal point. Python supports arbitrarily large integers.
๐ 1.1 Creating Integers
Assign integers directly, or use int() to convert from strings or other types.
Step-by-step explanation:
- Step 1: Assign integer literals:
x = 42,y = -17. - Step 2: Use
int()to convert a string:int("100"). - Step 3: Use
int()with a base:int("1010", 2)for binary. - Step 4: Check the type with
type().
x = 42 y = -17 z = int("100") binary = int("1010", 2) print(f"x = {x}, type: {type(x)}") print(f"y = {y}, type: {type(y)}") print(f"z = {z}, type: {type(z)}") print(f"binary = {binary}, type: {type(binary)}")
๐ 1.2 Arbitrary Precision
Python integers can grow to any size โ limited only by your system's memory.
Step-by-step explanation:
- Step 1: Create a very large integer:
big = 10 ** 100. - Step 2: Print the number of digits:
len(str(big)). - Step 3: Perform arithmetic on huge integers without overflow.
big = 10 ** 100 print(f"10^100 = {big}") print(f"Digits: {len(str(big))}") huge = big * big print(f"10^100 * 10^100 = 10^200") print(f"Digits in huge: {len(str(huge))}")
๐ง Floating-Point Numbers
Floats represent real numbers. They are implemented using double-precision (64-bit) IEEE 754.
๐ 2.1 Creating Floats
Use decimal points, scientific notation, or float() to create floats.
Step-by-step explanation:
- Step 1: Assign float literals:
pi = 3.14159,neg = -2.5. - Step 2: Use scientific notation:
e = 1.6e-19(electron charge). - Step 3: Convert using
float():float("3.14").
pi = 3.14159 neg = -2.5 e_charge = 1.6e-19 from_str = float("3.14") print(f"pi = {pi}, type: {type(pi)}") print(f"neg = {neg}, type: {type(neg)}") print(f"e_charge = {e_charge}, type: {type(e_charge)}") print(f"from_str = {from_str}, type: {type(from_str)}")
๐ 2.2 Special Float Values
Python floats include special values: inf, -inf, and nan.
Step-by-step explanation:
- Step 1: Create infinity:
inf = float("inf"). - Step 2: Create not-a-number:
nan = float("nan"). - Step 3: Check for infinity using
math.isinf()and NaN usingmath.isnan().
import math inf = float("inf") neg_inf = float("-inf") nan = float("nan") print(f"inf = {inf}, isinf: {math.isinf(inf)}") print(f"neg_inf = {neg_inf}, isinf: {math.isinf(neg_inf)}") print(f"nan = {nan}, isnan: {math.isnan(nan)}") print(f"inf + 5 = {inf + 5}") print(f"inf / inf = {inf / inf}")
nan == nan is False. Always use math.isnan() to test for NaN.โก Complex Numbers
Python has built-in support for complex numbers, using j as the imaginary unit.
๐ 3.1 Creating Complex Numbers
Use j or J for the imaginary part, or complex().
Step-by-step explanation:
- Step 1: Create a complex number:
z = 3 + 4j. - Step 2: Use
complex(real, imag):z2 = complex(2, -1). - Step 3: Access real and imaginary parts:
z.real,z.imag. - Step 4: Get the conjugate:
z.conjugate().
z = 3 + 4j z2 = complex(2, -1) print(f"z = {z}, type: {type(z)}") print(f"z2 = {z2}") print(f"z.real = {z.real}, z.imag = {z.imag}") print(f"z.conjugate() = {z.conjugate()}") print(f"z + z2 = {z + z2}") print(f"z * z2 = {z * z2}")
๐ 3.2 Complex Number Functions
The cmath module provides mathematical functions for complex numbers.
Step-by-step explanation:
- Step 1: Import
cmathfor complex math. - Step 2: Compute magnitude:
abs(z). - Step 3: Compute phase angle:
cmath.phase(z). - Step 4: Compute polar coordinates:
cmath.polar(z).
import cmath z = 3 + 4j print(f"z = {z}") print(f"|z| = {abs(z)}") print(f"phase(z) = {cmath.phase(z)} radians") print(f"polar(z) = {cmath.polar(z)}") r, theta = cmath.polar(z) print(f"rect(r, theta) = {cmath.rect(r, theta)}")
โ Arithmetic Operations
Python supports all standard arithmetic operators, plus some special ones.
๐ 4.1 Basic Operators
+, -, *, /, //, %, **
Step-by-step explanation:
- Step 1: Addition:
10 + 3. - Step 2: Subtraction:
10 - 3. - Step 3: Multiplication:
10 * 3. - Step 4: Division:
10 / 3returns float. - Step 5: Floor division:
10 // 3returns integer. - Step 6: Modulo (remainder):
10 % 3. - Step 7: Exponentiation:
10 ** 3.
a, b = 10, 3 print(f"a + b = {a + b}") print(f"a - b = {a - b}") print(f"a * b = {a * b}") print(f"a / b = {a / b}") print(f"a // b = {a // b}") print(f"a % b = {a % b}") print(f"a ** b = {a ** b}")
/ always returns a float. Use // for integer division.๐ 4.2 Augmented Assignment
Combine assignment with an operator: +=, -=, *=, etc.
Step-by-step explanation:
- Step 1: Start with
x = 10. - Step 2:
x += 3is equivalent tox = x + 3. - Step 3:
x *= 2is equivalent tox = x * 2.
x = 10 print(f"x = {x}") x += 3 print(f"x += 3 โ x = {x}") x -= 5 print(f"x -= 5 โ x = {x}") x *= 2 print(f"x *= 2 โ x = {x}") x //= 4 print(f"x //= 4 โ x = {x}") x **= 2 print(f"x **= 2 โ x = {x}")
๐ The math Module โ Advanced Mathematical Functions
Python's math module provides a wide range of mathematical functions.
๐ 5.1 Common math Functions
Trigonometry, logarithms, square roots, and more.
Step-by-step explanation:
- Step 1: Import
math. - Step 2: Square root:
math.sqrt(25). - Step 3: Trigonometry:
math.sin(math.pi / 2). - Step 4: Logarithms:
math.log(100, 10). - Step 5: Factorial:
math.factorial(5).
import math print(f"math.sqrt(25) = {math.sqrt(25)}") print(f"math.pi = {math.pi}") print(f"math.sin(math.pi/2) = {math.sin(math.pi/2)}") print(f"math.log(100, 10) = {math.log(100, 10)}") print(f"math.log2(8) = {math.log2(8)}") print(f"math.factorial(5) = {math.factorial(5)}") print(f"math.comb(5, 2) = {math.comb(5, 2)}")
๐ 5.2 Constants and Special Functions
math includes constants like pi, e, and tau, plus functions like ceil, floor, gcd.
Step-by-step explanation:
- Step 1: Constants:
math.e,math.tau. - Step 2: Ceiling and floor:
math.ceil(3.14),math.floor(3.14). - Step 3: Greatest common divisor:
math.gcd(48, 18).
import math print(f"math.e = {math.e}") print(f"math.tau = {math.tau} (2*pi)") print(f"math.ceil(3.14) = {math.ceil(3.14)}") print(f"math.floor(3.14) = {math.floor(3.14)}") print(f"math.gcd(48, 18) = {math.gcd(48, 18)}") print(f"math.isclose(0.1 + 0.2, 0.3) = {math.isclose(0.1 + 0.2, 0.3)}")
๐ฒ Random Numbers โ The random Module
Generate random numbers for games, simulations, testing, and more.
๐ 6.1 Basic Random Functions
random.random(), random.randint(), random.choice(), random.shuffle().
Step-by-step explanation:
- Step 1: Import
random. - Step 2: Generate a random float between 0 and 1:
random.random(). - Step 3: Generate a random integer:
random.randint(1, 10). - Step 4: Choose a random element:
random.choice(["a", "b", "c"]). - Step 5: Shuffle a list in place:
random.shuffle(items).
import random print(f"random.random() = {random.random()}") print(f"random.randint(1, 10) = {random.randint(1, 10)}") colors = ["red", "green", "blue"] print(f"random.choice(colors) = {random.choice(colors)}") items = [1, 2, 3, 4, 5] random.shuffle(items) print(f"shuffled items = {items}") sample = random.sample(range(100), 5) print(f"random.sample(100, 5) = {sample}")
๐ 6.2 Seeding for Reproducibility
Use random.seed() to get reproducible random sequences.
Step-by-step explanation:
- Step 1: Seed the random generator:
random.seed(42). - Step 2: Generate random numbers โ they will be the same every time.
- Step 3: This is essential for reproducible research and debugging.
import random random.seed(42) print("First sequence (seed=42):") for i in range(3): print(f" {random.randint(1, 100)}") random.seed(42) print("Second sequence (seed=42):") for i in range(3): print(f" {random.randint(1, 100)}")
๐ฐ Decimal & Fraction โ Exact Numbers
For precise decimal arithmetic and rational numbers, use Decimal and Fraction.
๐ 7.1 Decimal โ Exact Decimal Arithmetic
Avoid floating-point rounding errors with Decimal. Essential for financial applications.
Step-by-step explanation:
- Step 1: Import
Decimalfromdecimal. - Step 2: Create Decimals from strings:
Decimal("0.1"). - Step 3: Compare float vs Decimal precision.
- Step 4: Set precision with
getcontext().prec.
from decimal import Decimal, getcontext print("Float: 0.1 + 0.2 =", 0.1 + 0.2) print("Decimal: 0.1 + 0.2 =", Decimal("0.1") + Decimal("0.2")) getcontext().prec = 4 print("Precision 4:", Decimal("1") / Decimal("3")) price = Decimal("19.99") tax_rate = Decimal("0.08") total = price + (price * tax_rate) print(f"Price: ${price}, Total with tax: ${total}")
Decimal from strings or integers, not floats, to avoid floating-point inaccuracies.๐ 7.2 Fraction โ Rational Numbers
Represent exact rational numbers with Fraction from the fractions module.
Step-by-step explanation:
- Step 1: Import
Fractionfromfractions. - Step 2: Create fractions:
Fraction(3, 4). - Step 3: Perform arithmetic and see simplification.
from fractions import Fraction f1 = Fraction(3, 4) f2 = Fraction(1, 6) print(f"f1 = {f1}") print(f"f2 = {f2}") print(f"f1 + f2 = {f1 + f2}") print(f"f1 * f2 = {f1 * f2}") print(f"f1 / f2 = {f1 / f2}") f3 = Fraction("0.125") print(f"Fraction('0.125') = {f3}")
๐ฏ Number Formatting
Control how numbers are displayed with f-strings and the format() function.
๐ 8.1 Formatting Floats
Control decimal places, alignment, and thousands separators.
Step-by-step explanation:
- Step 1: Use
:.2ffor 2 decimal places. - Step 2: Use
:,for thousands separators. - Step 3: Use
:.2%for percentages. - Step 4: Use
:.2efor scientific notation.
pi = 3.14159265359 big = 1234567.89 print(f"pi to 2 decimals: {pi:.2f}") print(f"pi to 4 decimals: {pi:.4f}") print(f"pi in scientific: {pi:.2e}") print(f"big with commas: {big:,.2f}") pct = 0.875 print(f"percentage: {pct:.2%}")
๐ 8.2 Formatting Integers
Format integers with width, padding, and different bases.
Step-by-step explanation:
- Step 1: Use
:dfor integer (default). - Step 2: Use
:bfor binary,:ofor octal,:xfor hex. - Step 3: Use
:05dto pad with zeros.
n = 42 print(f"decimal: {n:d}") print(f"binary: {n:b}") print(f"octal: {n:o}") print(f"hex: {n:x}") print(f"hex (uppercase): {n:X}") print(f"padded: {n:05d}") print(f"padded with spaces: {n:5d}")
โ Frequently Asked Questions โ Python Numbers
Common questions about numbers in Python, answered.
Why does 0.1 + 0.2 give 0.30000000000000004?
+This is due to floating-point representation. Binary floating-point cannot represent 0.1 exactly. Use Decimal for exact decimal arithmetic, or round the result.
What is the difference between float and Decimal?
+float is fast and uses hardware-accelerated binary arithmetic but has rounding errors. Decimal is slower but provides exact decimal arithmetic, making it suitable for financial applications.
When should I use Fraction?
+Use Fraction when you need exact rational arithmetic โ for example, in mathematical proofs, educational software, or when working with ratios.
How do I generate a random number in a specific range?
+Use random.randint(a, b) for integers between a and b inclusive, or random.uniform(a, b) for floats between a and b.
What are math.inf and math.nan?
+math.inf represents infinity, and math.nan represents "Not a Number". They are used to handle special cases in mathematical computations.
How do I format a number with thousands separators?
+Use f"{number:,}" for integers, or f"{number:,.2f}" for floats with 2 decimal places.
What is the maximum size of an integer in Python?
+Python integers are arbitrary precision โ they can grow to any size limited only by your system's available memory. There is no fixed maximum.
๐ You've Mastered Python Numbers
From integers and floats to complex numbers, from basic arithmetic to advanced math, random generation, and precise decimal arithmetic โ you now have a complete toolkit for working with numbers in Python. You've learned to handle every numeric situation with confidence.
This curriculum, crafted by @PoeticGlenn, is your go-to reference for numeric computing in Python. Whether you're building financial systems, scientific simulations, or games, you have the skills to succeed.
"Numbers are the invisible language that powers the universe. Now you speak it fluently." โ Glenn Junsay Pansensoy (@PoeticGlenn)