Study guide
2.4 Standard Library Modules and Pip
OpenEDG PCAP — Certified Associate in Python Programming Exam
Track your progress as you read
Finished sections get a check mark.
1 Chapter 1: The PCAP-31-03 Exam Blueprint and Test-Day Logistics
1.1 The PCAP-31-03 Blueprint, Scoring, and Exam-Day Logistics
2 Chapter 2: Modules, Packages, and the Standard Library
2.1 Module Imports and Namespace Mechanics 2.2 Module Construction and Execution 2.3 Package Hierarchy and Navigation 2.4 Standard Library Modules and Pip
3 Chapter 3: Exceptions and Error Handling
3.1 Exception Control Flow and Syntax 3.2 The Built-in Exception Hierarchy 3.3 Raising Exceptions and Assertions 3.4 Custom Exceptions and Exception Chaining
4 Chapter 4: Strings, Encodings, and Text Processing
4.1 Character Encodings and String Immutability 4.2 String Indexing, Slicing, and Comparison 4.3 String Inspection and Classification Methods 4.4 String Transformation and Formatting Methods 4.5 Iterating, Sorting, and Comparing Strings Against Other Types
5 Chapter 5: Object-Oriented Programming Fundamentals
5.1 Classes, Instances, and Attributes 5.2 Encapsulation, Privacy, and Name Mangling 5.3 Dunder Methods and Object Lifecycle 5.4 Discovering Class Structure: __name__, __module__, __bases__, and Identity
6 Chapter 6: Advanced OOP, Inheritance, and Metaprogramming
6.1 Single Inheritance, Method Overriding, and Polymorphism 6.2 Multiple Inheritance and Method Resolution Order (MRO) 6.3 Class Methods, Static Methods, and Properties
7 Chapter 7: Functional Python, Comprehensions, and Closures
7.1 List, Dictionary, and Set Comprehensions 7.2 Lambda Expressions and Higher-Order Functions 7.3 Variable Scopes, the LEGB Rule, and Closures
8 Chapter 8: Iterators, Generators, and File I/O
8.1 Iterators and the Iteration Protocol 8.2 Generator Functions and Generator Expressions 8.3 File Input/Output and Context Managers 8.4 Predefined Streams, Handles vs. Streams, and errno Diagnostics
2.4 Standard Library Modules and Pip
Key Takeaways Explain This Topic AI
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.
Last updated: August 2026
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 π = 3.141592653589793 \pi = 3.141592653589793 π = 3.141592653589793
- math.e : Euler's number e = 2.718281828459045 e = 2.718281828459045 e = 2.718281828459045
math.tau : The circle constant τ = 2 π = 6.283185307179586 \tau = 2\pi = 6.283185307179586 τ = 2 π = 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 ≤ x \le x ≤ x (rounds toward − ∞ -\infty − ∞ ) 3 3 -4 -4
- math.ceil(x) Smallest integer ≥ x \ge x ≥ x (rounds toward + ∞ +\infty + ∞ ) 4 4 -3 -3
- math.trunc(x) Truncates decimal part (rounds toward 0 0 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 2^{19937}-1 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 ) [0.0, 1.0) [ 0.0 , 1.0 ) float 0.0 ≤ x < 1.0 0.0 \le x < 1.0 0.0 ≤ x < 1.0 (exclusive of 1.0)
random.randint(a, b) [ a , b ] [a, b] [ a , b ] int a ≤ N ≤ b a \le N \le b a ≤ N ≤ b ( both endpoints INCLUSIVE )
random.randrange(stop) [ 0 , stop ) [0, \text{stop}) [ 0 , stop ) int 0 ≤ N < stop 0 \le N < \text{stop} 0 ≤ N < stop (stop EXCLUSIVE)
random.randrange(start, stop[, step]) [ start , stop ) [\text{start}, \text{stop}) [ start , stop ) with step int start ≤ N < stop \text{start} \le N < \text{stop} start ≤ N < 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 ( P ip I nstalls P ackages) 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 -y to 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 in requirements.txt format ( 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