2.4 Standard Library Modules and Pip
Key Takeaways
- The `math` module provides standard mathematical routines; `math.floor()` rounds down toward negative infinity, `math.ceil()` rounds up toward positive infinity, and `math.trunc()` truncates toward zero.
- The `random` module implements pseudo-random generators based on the Mersenne Twister; `random.randint(a, b)` includes both endpoints, while `random.randrange(a, b)` excludes `b`.
- `random.shuffle()` alters mutable sequences in-place and returns `None`, while `random.choice()` and `random.sample()` extract elements without modifying the input.
- The `platform` module introspects the host operating system, processor hardware, Python implementation (`CPython`), and runtime version tuples.
- `pip` manages package installation, dependency resolution via `requirements.txt`, package inspection (`pip show`), and uninstallation.
Standard Library Modules and Pip
Python's philosophy of "batteries included" means the standard installation comes packaged with a rich suite of built-in modules. The PCAP exam focuses heavily on three foundational standard library modules—math, random, and platform—as well as third-party package management via pip.
1. The math Module
The math module provides access to underlying C-standard mathematical functions for floating-point calculations. All functions in math operate on numbers and convert results to floats where applicable.
Mathematical Constants
math.pi: The mathematical constant $\pi = 3.141592653589793$math.e: Euler's number $e = 2.718281828459045$math.tau: The circle constant $\tau = 2\pi = 6.283185307179586$math.inf: Floating-point positive infinity (float('inf'))math.nan: Floating-point "Not a Number" (float('nan'))
Rounding, Truncation, and Integer Conversion (High PCAP Exam Frequency)
Understanding the exact difference between floor(), ceil(), and trunc() is a classic PCAP testing area, particularly with negative numbers:
| Function | Behavior | 3.7 | 3.2 | -3.2 | -3.7 |
|---|---|---|---|---|---|
math.floor(x) | Largest integer $\le x$ (rounds toward $-\infty$) | 3 | 3 | -4 | -4 |
math.ceil(x) | Smallest integer $\ge x$ (rounds toward $+\infty$) | 4 | 4 | -3 | -3 |
math.trunc(x) | Truncates decimal part (rounds toward $0$) | 3 | 3 | -3 | -3 |
import math
# Positive Numbers
print(math.floor(4.9)) # 4
print(math.ceil(4.1)) # 5
print(math.trunc(4.9)) # 4
# Negative Numbers (CRITICAL!)
print(math.floor(-4.1)) # -5 (smaller than -4.1)
print(math.ceil(-4.9)) # -4 (greater than -4.9)
print(math.trunc(-4.9)) # -4 (chops off .9 toward zero)
Roots, Powers, Factorials, and Geometry
import math
# Square root (x must be >= 0, otherwise raises ValueError)
print(math.sqrt(64)) # 8.0 (always returns a float)
# Hypotenuse: sqrt(x*x + y*y)
print(math.hypot(3, 4)) # 5.0
# Power: always returns float
print(math.pow(2, 3)) # 8.0 (contrast with 2 ** 3 which returns int 8)
# Factorial: accepts non-negative integers only
print(math.factorial(5)) # 120 (5 * 4 * 3 * 2 * 1)
# Logarithms: math.log(x[, base]) defaults to natural log (base e)
print(math.log(math.e)) # 1.0
print(math.log(100, 10)) # 2.0
print(math.log2(8)) # 3.0
print(math.log10(1000)) # 3.0
# Trigonometry: arguments MUST be in radians
angle_rad = math.radians(90) # Convert degrees to radians
print(math.sin(angle_rad)) # 1.0
print(math.degrees(math.pi)) # 180.0 (Convert radians to degrees)
2. The random Module
The random module implements pseudo-random number generators (PRNG) powered by the Mersenne Twister algorithm (period $2^{19937}-1$). These generators are deterministic and not cryptographically secure.
The seed() Function
The generator's sequence is determined by an initial state (the seed). By default, Python seeds from system time or OS randomness. Setting a fixed seed produces a 100% reproducible sequence:
import random
random.seed(42)
print(random.random()) # 0.6394267984578837
# Re-seeding with 42 reproduces the identical number
random.seed(42)
print(random.random()) # 0.6394267984578837
Generating Numbers: random(), randint(), and randrange()
| Function | Range | Type | Inclusivity |
|---|---|---|---|
random.random() | $[0.0, 1.0)$ | float | $0.0 \le x < 1.0$ (exclusive of 1.0) |
random.randint(a, b) | $[a, b]$ | int | $a \le N \le b$ (both endpoints INCLUSIVE) |
random.randrange(stop) | $[0, \text{stop})$ | int | $0 \le N < \text{stop}$ (stop EXCLUSIVE) |
random.randrange(start, stop[, step]) | $[\text{start}, \text{stop})$ with step | int | $\text{start} \le N < \text{stop}$ (stop EXCLUSIVE) |
import random
# Float in [0.0, 1.0)
print(random.random())
# Integer between 1 and 6 inclusive (like rolling a standard die)
die_roll = random.randint(1, 6) # Can produce 1, 2, 3, 4, 5, or 6
# Even integer between 0 and 10 exclusive (0, 2, 4, 6, 8)
even_num = random.randrange(0, 10, 2) # Will NEVER produce 10!
Sequence Operations: choice(), sample(), and shuffle()
import random
letters = ['A', 'B', 'C', 'D', 'E']
# 1. choice(seq): Returns one random element
print(random.choice(letters)) # e.g., 'C'
# 2. sample(population, k): Returns k UNIQUE random elements (without replacement)
sample_items = random.sample(letters, 3)
print(sample_items) # e.g., ['D', 'A', 'E']
# Note: If k > len(population), raises ValueError
# 3. shuffle(seq): Shuffles mutable list IN-PLACE and returns None!
cards = [1, 2, 3, 4, 5]
result = random.shuffle(cards)
print("Return value:", result) # None
print("Shuffled list:", cards) # e.g., [3, 1, 5, 2, 4]
3. The platform Module
The platform module queries the underlying hardware, operating system, and Python interpreter environment.
OS and Hardware Introspection
import platform
# Comprehensive platform string (e.g., 'macOS-14.4-arm64-arm-64bit' or 'Linux-5.15.0-x86_64')
print(platform.platform())
print(platform.platform(terse=True)) # Shortened platform string
# Hardware Architecture
print(platform.machine()) # e.g., 'x86_64' or 'arm64'
print(platform.processor()) # e.g., 'arm' or 'Intel64 Family 6 Model 158'
# Operating System Details
print(platform.system()) # e.g., 'Darwin', 'Linux', 'Windows'
print(platform.version()) # OS build version string
Python Implementation and Version Introspection
| Function | Return Type | Example Value | Description |
|---|---|---|---|
platform.python_implementation() | str | 'CPython' | Interpreter implementation (CPython, PyPy, Jython, IronPython) |
platform.python_version() | str | '3.12.2' | Python version as a single formatted string |
platform.python_version_tuple() | tuple[str] | ('3', '12', '2') | 3-tuple of version parts (strings, not ints!) |
import platform
print(platform.python_implementation()) # 'CPython'
print(platform.python_version()) # '3.12.2'
ver_tuple = platform.python_version_tuple()
print(ver_tuple) # ('3', '12', '2')
print(type(ver_tuple[0])) # <class 'str'> -- Elements are strings!
4. Package Management with pip
pip (Pip Installs Packages) is the standard package manager for Python, used to download and install packages from the Python Package Index (PyPI).
Essential pip Commands
pip install <package>: Downloads and installs the latest version of a package (e.g.,pip install requests).pip install <package>==1.4.2: Installs a specific pinned version.pip install --upgrade <package>(or-U): Upgrades an existing package to the latest release.pip uninstall <package>: Uninstalls a package (use-yto suppress confirmation prompts).pip list: Lists all currently installed packages and their versions.pip show <package>: Displays detailed package metadata (author, version, install location, requirements).pip freeze: Outputs installed packages inrequirements.txtformat (package==version).pip search <query>: Historically searched PyPI from CLI (now disabled by PyPI due to load, but historically tested in PCAP).
Dependency Management with requirements.txt
A requirements.txt file specifies project dependencies:
requests==2.31.0
numpy>=1.24.0
pytest~=7.4.0
To install all specified dependencies into an environment:
pip install -r requirements.txt
What is the output of executing the following code snippet?
import math
print(math.floor(-5.2), math.trunc(-5.2))
Which of the following expressions will NEVER return the integer 10?
A programmer writes the following code to shuffle a deck of cards:
What is printed to the console?import random
deck = ['Ace', 'King', 'Queen', 'Jack']
shuffled_deck = random.shuffle(deck)
print(shuffled_deck)
What is the data type of the elements inside the tuple returned by platform.python_version_tuple()?