Numbers in Python
Numbers in Python
Section titled “Numbers in Python”Introduction
Section titled “Introduction”Python provides several numeric types: integers (with unlimited precision), floats (IEEE 754 double-precision), complex numbers, booleans, and more through the standard library.
Integers (int)
Section titled “Integers (int)”x = 42y = -100
# Arbitrary precision!big = 2 ** 1000 # 302-digit number — no overflow!
# Different basesbinary = 0b1010 # Binary → 10octal = 0o17 # Octal → 15hex_num = 0xFF # Hex → 255
# Readable large numbersmillion = 1_000_000
# Operationsprint(abs(-42)) # 42print(pow(2, 10, 1000)) # 24 — modular exponentiationFloats
Section titled “Floats”pi = 3.14159large = 1.5e10 # Scientific notation
# Special valuesimport mathprint(float('inf')) # inf (infinity)print(float('nan')) # nan (Not a Number)Complex Numbers
Section titled “Complex Numbers”c1 = 2 + 3jprint(c1.real) # 2.0print(c1.imag) # 3.0print(c1.conjugate()) # (2-3j)Booleans (bool)
Section titled “Booleans (bool)”print(True) # Trueprint(False) # Falseprint(isinstance(True, int)) # True! bool is subclass of intprint(True + True) # 2Decimal & Fractions
Section titled “Decimal & Fractions”from decimal import Decimal, getcontext
# Exact decimal arithmetica = Decimal("0.1")b = Decimal("0.2")print(a + b) # 0.3 — exact!
from fractions import Fractiona = Fraction(1, 3)b = Fraction(1, 6)print(a + b) # 1/2 (exact!)Why It Matters
Section titled “Why It Matters”Choosing the right numeric type is critical for accuracy (financial calculations need Decimal) and performance (float for scientific computing).
Common Mistakes
Section titled “Common Mistakes”- Using float for financial calculations (use Decimal!)
- Expecting exact float arithmetic (
0.1 + 0.2 = 0.30000000000000004)
Interview Questions
Section titled “Interview Questions”Q1: Why does 0.1 + 0.2 not equal 0.3?
A: Binary can’t represent 0.1 exactly (repeating fraction). Use Decimal for exact decimal arithmetic.
Q2: What is arbitrary precision in Python integers?
A: Python 3 integers can be arbitrarily large, limited only by available memory. No overflow errors like in C/Java.
Practice Exercises
Section titled “Practice Exercises”- Calculate compound interest using Decimal for accuracy.
- Compare float vs Decimal for 0.1 + 0.2.
- Convert between binary, octal, hex, and decimal.