Modules and the Standard Library
Definition and Purpose
A module is a file containing Python definitions and statements intended for
use in other Python programs. Python includes many modules as part of the
standard library.
The random Module
randrange() Method
The randrange() method generates an integer between its lower and upper
arguments using the same semantics as range():
• Lower bound is included
• Upper bound is excluded
• All values have equal probability of occurring (uniformly distributed)
• Accepts an optional step argument
Example: To generate a random odd number less than 100:
python
random_odd = [Link](1, 100, 2)
Pseudo-Random Generators and Repeatability
• Random number generators are based on deterministic algorithms —
they are repeatable and predictable, making them pseudo-random
generators rather than genuinely random
• Generators start with a seed value
• Each call for a random number produces a result based on the current
seed, and the seed state is updated
1
• For debugging and unit testing, repeatability is valuable — programs can
be made to do the same thing every time by initializing the generator with
a known seed
• Note: Repeatability is typically only desired during testing; in applications
like card games, consistent shu ling would reduce novelty
Performance Considerations
The "shu le and slice" algorithm is ine icient when selecting a few elements
from a very large domain. For example, generating five numbers between 1
and 10 million without duplicates by creating a list of 10 million items, shu ling
it, and slicing would be a performance disaster.
The time Module
The time module is used to measure code e iciency and execution speed.
• The clock() function returns a floating-point number representing
seconds elapsed since the program started running
• Measurement procedure:
• Call clock() before executing code to measure; assign result to a
variable (e.g., t0)
• Execute the code
• Call clock() again; assign result to another variable (e.g., t1)
• Calculate elapsed time: t1 - t0
This approach allows comparison of performance between di erent
implementations (e.g., built-in sum() function vs. custom summation code).
The math Module
The math module contains standard mathematical functions typically found
on a calculator and mathematical constants:
2
• Functions: sin, cos, sqrt, asin, log, log10
• Constants: pi, e
Namespaces, Scope, and Module Organization
Namespaces
A namespace is a collection of identifiers that belong to a module or function.
Namespaces group related items together—for example, all math functions
or operations involving random numbers.
Each module has its own namespace, allowing the same identifier name to be
used in multiple modules without causing naming conflicts. This enables
multiple programmers to work on the same project without naming collisions.
Relationship Between Namespaces, Files, and Modules
Python implements a one-to-one mapping: one file corresponds to one
module, which corresponds to one namespace. The module name is derived
from the filename, and this becomes the namespace name.
• [Link] (filename) → math (module name) → math (namespace)
In Python, these concepts are largely interchangeable. However, other
languages (e.g., C#) allow one module to span multiple files, one file to contain
multiple namespaces, or multiple files to share the same namespace.
Key distinction: Files and directories organize storage location on the
computer, while namespaces and modules are programming concepts for
organizing related functions and a ributes. They should not necessarily
coincide with file and directory structures.
Renaming a file in Python changes its module name, requiring updates to
3
import statements and all code referencing functions or a ributes within that
namespace.
Scope and Lookup Rules
Scope is the region in which a variable is visible. When a function defines
variables with the same name as global variables, the scope lookup rules
determine which variable is used based on context.
• Variables in the global namespace are accessible throughout the module
• Variables in the local namespace of a function are created during
function execution and are only visible within that function
• Local variables shadow (hide) global variables with the same name within
the function body
• After the function returns, references to those names revert to the original
global variables
The def statement places the function name into the global namespace,
making it callable from anywhere in the module.
A ributes and the Dot Operator
Variables defined inside a module are called a ributes of the module.
Objects also have a ributes (e.g., __doc__, __annotations__).
A ributes are accessed using the dot operator (.):
• [Link] accesses the question a ribute of module1
• seqtools.remove_at accesses the remove_at function in the seqtools
module
A fully qualified name explicitly specifies which a ribute is being referenced
by including the module or object name before the dot.
4
Data Types and Object-Oriented Programming
Fundamentals
Object-Oriented Programming (OOP)
Object-oriented programming is a programming paradigm that provides
features to support the creation and manipulation of objects. Python is an
object-oriented programming language.
• OOP emerged in the 1960s but became the dominant programming
paradigm in the mid-1980s
• Developed to handle rapidly increasing size and complexity of software
systems
• Makes it easier to modify large, complex systems over time
• Key di erence from procedural programming: OOP focuses on creating
objects that contain both data and functionality together, whereas
procedural programming focuses on writing functions that operate on
data
User-Defined Classes and Objects
Classes are templates for creating objects. A class contains the machinery to
make instances (objects) of that class.
• Class definitions typically appear near the beginning of a program (after
import statements)
• Syntax: Class definition begins with the keyword class, followed by the
class name, and ends with a colon
• Indentation levels indicate where the class ends
• If the first line after the class header is a string, it becomes the docstring
5
of the class
The __init__ Method
Every class should have a method with the special name __init__ (the
initializer method).
• Automatically called whenever a new instance of the class is created
• Gives the programmer the opportunity to set up the a ributes required
within the new instance
• The self parameter (by convention) is automatically set to reference the
newly created object that needs to be initialized
• Instantiation is the combined process of creating a new object and
initializing it to factory-default se ings
A ributes and Methods
A ributes are data values associated with an object. Methods are functions
that belong to a class and operate on instances of that class.
• Methods are accessed using dot notation (e.g., [Link](90))
• When defining a method, the first parameter refers to the instance being
manipulated (conventionally named self)
• The caller does not explicitly supply an argument for the self parameter
—this is handled automatically
• Methods can be passed objects as arguments in the usual way
Objects as Active Agents
In object-oriented programming, objects are considered the active agents,
not functions.
• Procedural style: print_time(current_time) — the function is the
active agent
6
• Object-oriented style: current_time.print_time() — the object is the
active agent
• This perspective mirrors real-life experience: functionality is tightly bound
inside objects themselves (e.g., a microwave's cook method is part of the
microwave, not a separate function)
• Shifting responsibility from functions to objects makes it possible to write
more versatile, maintainable, and reusable code
Object State
State refers to the data values stored within an object that can be updated
over time.
• Objects are most useful when they maintain state that is updated by
method calls
• Example: A turtle object's state includes position, heading, color, and
shape
• Methods update state (e.g., left(90) updates heading, forward()
changes position)
• Example: A bank account object's state includes current balance and
transaction log; methods allow querying balance, depositing funds, or
making payments
Converting Instances to Strings
A method can be added to a class to produce a string representation of an
instance.
• This approach is preferred over print functions that output directly
• Allows each instance to produce its own string representation
• Enables flexibility in how objects are displayed or used in di erent contexts
7
8