COMPUTER PROGRAMMING 1 (PYTHON) • FUNCTIONS & MODULARITY

Using Standard Library Modules — I can import and use standard library modules (e.g., math, random) at my level.

Unlock thousands of pre-built tools that ship with every Python installation.

Historical Context & Motivation

Every programmer eventually faces a familiar problem: you need to do something common—generate a random number, calculate a square root, or work with dates—and writing it from scratch feels like reinventing the wheel. This is the exact frustration that led to the creation of standard libraries, collections of pre-written code that ship alongside a programming language so developers can focus on solving new problems rather than re-solving old ones.

The idea of bundling reusable code with a language dates back to the earliest days of computing. As languages matured, so did the expectation that they would provide ready-made solutions for routine tasks. Python took this philosophy to heart with its famous motto: "batteries included." That phrase means Python ships with a rich standard library of over 200 modules covering everything from math to networking to file handling.

1957
FORTRAN's Math Library
FORTRAN, one of the earliest high-level languages, shipped with built-in mathematical routines like SQRT and SIN, pioneering the concept of a standard library.
1972
C Standard Library Born
The C programming language introduced a compact standard library (stdlib, stdio, math) that became the template for nearly every language that followed.
1991
Python 0.9 Released
Guido van Rossum released Python with a small set of built-in modules. From day one, Python was designed to be extensible through importable modules.
2000
Python 2.0 — "Batteries Included"
Python 2.0 dramatically expanded the standard library, cementing the "batteries included" philosophy. Modules like os, math, and random became staples.
2020s
Modern Python Standard Library
Python 3.x ships with over 200 modules. The standard library continues to grow, and developers rely on it daily for math, data processing, web services, and more.

The central question this lesson addresses is simple but powerful: how do you tap into Python's vast collection of ready-made tools? The answer lies in the import statement, a one-line command that makes an entire module's functions and constants available in your program.

Core Principles & Definitions

Before you start importing, it helps to understand the key vocabulary and ideas behind Python's module system. A module is simply a Python file (ending in .py) that contains functions, classes, and variables you can reuse. The standard library is the collection of modules that come pre-installed with every copy of Python—no downloading or installing required.

1

Module

A single .py file containing related functions, constants, and classes. Think of it as a toolbox dedicated to one category of tasks.
2

Import Statement

The command that loads a module into your program. The three main forms are import math, from math import sqrt, and import math as m.
3

Dot Notation

After importing a module, you access its contents using a dot: math.sqrt(25). The dot tells Python, "look inside this module for that name."
4

Namespace

A container that keeps names organized and prevents collisions. When you write import math, all of math's names live inside the math namespace, separate from your own variables.
5

"Batteries Included"

Python's guiding philosophy that the standard library should cover most common tasks out of the box, so programmers don't need to hunt for external packages for everyday work.
✦ KEY TAKEAWAY
Think of Python's standard library like a school supply closet. The supplies (functions) are already organized into labeled bins (modules). You don't need to buy anything—just walk over and grab the bin you need. The import statement is you opening that closet door.

Visual Explanation — How Import Works

The following diagram shows the relationship between your Python script, the import statement, and the standard library. When Python encounters an import line, it searches for the module, loads it into memory, and creates a namespace you can reference through dot notation.

The diagram shows how your script communicates with the Python runtime, which then loads the requested module (like math or random) and makes its functions available. The bottom panel compares the three main import styles.

Notice that Style 1 (full import) keeps everything in the module's namespace, so you always prefix calls with the module name. Style 2 (selective import) pulls specific names directly into your script, which is convenient but can cause name collisions if two modules share a function name. Style 3 (alias) gives the module a shorter nickname—useful for modules with long names. For beginners, Style 1 is the safest and most readable choice.

How Modules Work Under the Hood

While you don't need to memorize the internals, understanding the mechanism behind importing helps you debug issues and write cleaner code. When Python encounters import math, it performs a specific sequence of steps, and it only does the heavy lifting once—subsequent imports of the same module reuse the cached version.

The Import Search Path

Python looks for a module in a specific order. First, it checks its cache of already-imported modules (stored in sys.modules). If the module isn't cached, Python searches through a list of directories called the module search path. This path includes the directory of your script, the standard library directory, and any installed third-party packages.

Import Syntax Comparison

Four ways to import a module and their trade-offs
SyntaxWhat It DoesHow You Call Functions
import mathLoads the entire math module into its own namespacemath.sqrt(16)
from math import sqrt, piLoads only sqrt and pi directly into your script's namespacesqrt(16)
import math as mLoads the entire module but gives it the alias 'm'm.sqrt(16)
from math import *Loads ALL names from math into your namespace (not recommended)sqrt(16)
⚠️ Avoid from module import *
Using from math import * dumps every name from that module into your script. If two modules define a function with the same name, the second import silently overwrites the first. This makes bugs hard to track down. Stick with import math or selectively import only what you need.

Exploring a Module with dir()

Curious what's inside a module? Python provides a built-in function called dir() that lists all names defined in a module. For example, after import math, running print(dir(math)) outputs a list of every function and constant in the math module. You can also use help(math.sqrt) to read the documentation for any specific function directly in the Python shell.

Exploring Key Standard Library Modules

Python's standard library is enormous, but two modules stand out as especially useful for beginning programmers: math and random. Let's explore what each one offers.

A reference card of beginner-friendly standard library modules. The top row highlights the two most commonly used modules (math and random), while the middle row and bottom panel show additional modules you'll encounter as you progress.

The math Module in Depth

The math module gives you access to mathematical constants like math.pi (≈ 3.14159) and math.e (≈ 2.71828), as well as functions for square roots, trigonometry, logarithms, rounding, and more. A key distinction: math.sqrt() always returns a float, while Python's built-in ** operator can return either an int or a float. Also, math.ceil() rounds up to the nearest integer, while math.floor() rounds down—both return int values.

The random Module in Depth

The random module produces pseudo-random numbers—they appear random but are generated by a mathematical algorithm. The function random.randint(a, b) returns a random integer between a and b (inclusive on both ends), which is perfect for simulating dice rolls or picking lottery numbers. The function random.choice() picks a random element from a list, and random.shuffle() rearranges a list in place (it modifies the original list rather than returning a new one).

Worked Example — Building a Circle Calculator & Dice Game

Let's walk through two mini-programs that demonstrate how to import and use the math and random modules in practical scenarios.

Example 1: Circle Area & Circumference Calculator
1
Step 1 — Import the math moduleAt the top of your script, write import math. This gives you access to math.pi and all math functions. By convention, import statements always go at the very top of the file.
import math
2
Step 2 — Get user input for the radiusUse input() to ask the user for a radius and convert it to a float, since radii can be decimal values.
radius = float(input("Enter the radius: "))
3
Step 3 — Calculate area using math.piThe area of a circle is π × r². We use math.pi for a precise value of π and Python's ** operator to square the radius.
area = math.pi * radius ** 2
4
Step 4 — Calculate circumferenceCircumference is 2 × π × r. Again, math.pi provides precision far beyond typing 3.14 yourself.
circumference = 2 * math.pi * radius
5
Step 5 — Display results with roundingUse Python's built-in round() function to display two decimal places. For a radius of 5, area ≈ 78.54 and circumference ≈ 31.42.
print("Area:", round(area, 2)) # 78.54 print("Circumference:", round(circumference, 2)) # 31.42
Example 2: Dice-Rolling Simulator
1
Step 1 — Import the random moduleWrite import random at the top. This gives you access to functions that generate random numbers.
import random
2
Step 2 — Simulate rolling two diceUse random.randint(1, 6) to simulate a standard six-sided die. Call it twice for two separate dice.
die1 = random.randint(1, 6) die2 = random.randint(1, 6)
3
Step 3 — Calculate and display the totalAdd the two dice together and display the individual rolls plus the total. Each time you run this program, you'll get different results because the numbers are random.
total = die1 + die2 print(f"Die 1: {die1}, Die 2: {die2}, Total: {total}")
4
Step 4 — Add a loop for multiple rollsWrap the logic in a for loop to roll multiple times. This is where modules really shine—you'd need pages of code to build a random number generator from scratch.
for i in range(5): roll = random.randint(1, 6) print(f"Roll {i+1}: {roll}")

Comparing Import Styles — Strengths & Limitations

Each import style has trade-offs. Choosing the right one depends on how many functions you need, whether readability or brevity matters more, and how much you want to protect your namespace from name collisions.

Trade-offs of Python's four import styles
Import StyleStrengthsLimitations
import mathClear origin of every function; no name collisions; easy to search code for all uses of the moduleSlightly longer function calls (e.g., math.sqrt() vs. sqrt())
from math import sqrt, piShorter calls; only imports what you need; makes code concise when using just one or two functionsPossible name collisions if you import sqrt from another module; harder to tell where a function came from
import math as mShorter prefix while keeping namespace safety; widely used for long module names (e.g., import numpy as np)Alias must be memorable; non-standard aliases confuse other readers
from math import *Maximum brevity; useful in quick interactive sessionsPollutes namespace; hard to debug; silent overwrites; strongly discouraged in production code
✦ KEY TAKEAWAY
Think of import math like borrowing an entire labeled toolbox—you always know which toolbox a tool came from. from math import sqrt is like taking just the wrench out and setting it on your workbench. It's faster to grab, but if you have two different wrenches lying around, you might grab the wrong one. For classroom projects, import module_name is almost always the clearest choice.

Connection to Advanced Concepts

The standard library is just the beginning. As you grow as a programmer, you'll encounter third-party packages—modules written by other developers and shared through the Python Package Index (PyPI). You install them using a tool called pip. The import syntax is identical to what you've learned here, which is why mastering standard library imports now pays off later.

From standard library basics to advanced modularity
ConceptWhat You Know NowWhat Comes Next
Importing modulesimport math — standard library modulesimport numpy — third-party packages installed via pip
Creating modulesUsing pre-built modulesWriting your own .py files and importing them into other scripts
PackagesSingle-file modulesFolders containing multiple modules with an __init__.py file
Virtual environmentsNot needed yetIsolated project environments to manage dependencies

You'll also learn to create your own modules by saving functions in a separate .py file and importing them—exactly the same way Python imports its own standard library. Eventually, you may organize related modules into packages (folders of modules), manage dependencies with virtual environments, and even publish your own packages to PyPI for others to use. The foundation for all of that starts with the simple import statement you're mastering today.

Practice Problems

PROBLEM 1 — CONCEPTUAL
Explain the difference between import math and from math import sqrt. Why might a programmer prefer one over the other?
PROBLEM 2 — BASIC CALCULATION
Write a short Python program that uses the math module to compute and print the hypotenuse of a right triangle with legs of length 3 and 4. Use math.sqrt().
PROBLEM 3 — INTERMEDIATE
Write a program that uses the random module to simulate flipping a coin 100 times. Count and print how many times "Heads" and "Tails" each appear. Hint: use random.choice(["Heads", "Tails"]) inside a loop.
PROBLEM 4 — APPLIED
A teacher wants a program that generates a unique 4-question math quiz each time it runs. Each question should ask "What is a + b?" where a and b are random integers between 1 and 50. Use random.randint() and math.floor() (to score percentage). Write the program.
PROBLEM 5 — CRITICAL THINKING
A classmate writes from math import * and from random import * at the top of their program, then calls log(100). They're confused because both modules define a function named log (math's logarithm vs. random's internal logging). Explain what goes wrong, which version of log Python will use, and how to fix the code using better import practices.

Lesson Summary

Python's standard library is a massive collection of pre-built modules that come installed with every copy of Python—no extra downloads needed. You access these modules using the import statement, which has three main forms: import math (full import with dot notation), from math import sqrt (selective import), and import math as m (alias import). Each style has trade-offs between readability and brevity, but the full import style is the safest for beginners because it keeps namespaces clean and makes your code easy to debug.

The math module provides essential mathematical functions like sqrt(), ceil(), and floor(), plus constants like pi and e. The random module generates pseudo-random numbers using functions like randint(), choice(), and shuffle(). Mastering standard library imports lays the groundwork for working with third-party packages, creating your own modules, and building larger, well-organized Python projects.

Varsity Tutors • Computer Programming 1 (Python) • Using Standard Library Modules