Skip to content
PythonModules, Files, and Errorsbeginner22 min read

Useful Standard Library Tools

Use Python's math, statistics, random, pathlib, and datetime modules to solve common programming tasks.

In this lesson, you will learn

  • ✓Explain what Python's standard library is and why it is useful.
  • ✓Use math for common mathematical operations and statistics for basic numerical summaries.
  • ✓Use random to generate pseudorandom values and understand why results can vary.
  • ✓Use pathlib to inspect filesystem paths without manually manipulating path strings.
  • ✓Use datetime to represent dates and times and format them as strings.
  • ✓Trace examples, predict outputs, and choose an appropriate module for a practical task.

1. What is the Python standard library?

A module is a Python file or module object that provides reusable names, such as functions, classes, and constants. The standard library is the collection of modules distributed with Python.

You can import an entire module and access its names using dot notation, as in math.sqrt(25), or import a particular name, as in from statistics import mean. The examples in this lesson use both approaches.

The five modules in this lesson have distinct purposes: math provides mathematical functions, statistics summarizes numerical data, random generates pseudorandom values, pathlib works with filesystem paths, and datetime represents dates and times.

These modules are part of Python's standard library, so a separate package installation is normally unnecessary. Some modules interact with the environment: for example, pathlib can inspect or modify filesystem paths, while random can produce different results on different calls.

Import a function from a module

Import a function from a module
python
from statistics import mean
 
scores = [2, 4, 6]
average = mean(scores)
print(average)
Output
4

from statistics import mean makes the mean function available by the name mean. The list contains 2, 4, and 6. Their sum is 12, and 12 divided by 3 is 4. mean returns the arithmetic average. print displays the returned value. The displayed output is 4, not 4.0, for this example.

Note

Importing a module does not mean that every function in it runs automatically. Your code must call the functions or use the values it needs.

2. The math module

The math module provides mathematical functions and constants. It is useful for operations such as calculating square roots, rounding numbers upward or downward, and working with pi.

Import math to access its names through the module, such as math.sqrt(25). This makes it clear which module provides the function.

Be careful to distinguish mathematical functions from built-in functions. For example, abs() is built into Python, while sqrt() is provided by math.

Calculate a square root and round upward

Calculate a square root and round upward
python
import math
 
print(math.sqrt(25))
print(math.ceil(4.2))
print(math.floor(4.8))
Output
5.0 5 4

math.sqrt(25) returns 5.0. The square root is represented as a floating-point number. math.ceil(4.2) returns 5 because ceil rounds a number upward to the smallest integer greater than or equal to it. math.floor(4.8) returns 4 because floor rounds a number downward to the greatest integer less than or equal to it. ceil and floor do not simply round to the nearest integer. Their behavior is directional.

3. The statistics module

The statistics module provides functions for summarizing numerical data. Two useful beginner functions are mean() and median().

The mean is the arithmetic average: add the values and divide by the number of values. The median is the middle value after sorting the data. If there is an even number of values, the median is the arithmetic average of the two middle values.

These measures describe data differently. A very large or very small value can strongly affect the mean, while the median is often less affected by extreme values.

Calculate the mean and median

Calculate the mean and median
python
import statistics
 
values = [1, 9, 3]
print(statistics.mean(values))
print(statistics.median(values))
Output
4.333333333333333 3

The mean is (1 + 9 + 3) / 3, which is approximately 4.333333333333333. To find the median, sort the values mentally: [1, 3, 9]. The middle value is 3, so statistics.median(values) returns 3. The input list does not need to be sorted before calling median().

Note

Statistics functions generally expect suitable numerical data. For example, mean([]) raises StatisticsError because an empty dataset has no arithmetic mean.

4. The random module

The random module provides functions for generating pseudorandom values. Pseudorandom means the values are produced by an algorithm rather than by a source of guaranteed true randomness.

random.random() returns a floating-point number greater than or equal to 0.0 and less than 1.0. random.randint(a, b) returns an integer between a and b, including both endpoints. random.choice(sequence) selects one item from a non-empty sequence.

Because random values can vary, do not assume that a call always produces one fixed value. You can use random.seed() to make pseudorandom sequences reproducible for suitable testing scenarios.

The random module is not intended for security-sensitive operations such as generating password-reset tokens or secret authentication values. Use the secrets module for those tasks instead.

Generate a random integer

Generate a random integer
python
import random
 
number = random.randint(1, 6)
print(1 <= number <= 6)
Output
True

randint(1, 6) can return any integer from 1 through 6, including both endpoints. The comparison checks whether the generated number is within the permitted range. The exact number is unpredictable in an ordinary run, but the range check is True for every valid result.

5. The pathlib module

The pathlib module provides the Path class for representing and working with filesystem paths. It offers methods and properties that are usually clearer than manually joining or splitting path strings.

A Path object can represent a path whether or not the corresponding file currently exists. Creating a Path object does not create a file on disk.

Useful properties include name, which returns the final path component, suffix, which returns the final file extension including its dot, and parent, which represents the containing path.

Path behavior can depend on the operating system and the kind of path being used. The examples here use simple relative paths and do not require a file to exist.

Inspect a file path

Inspect a file path
python
from pathlib import Path
 
path = Path('notes.txt')
print(path.name)
print(path.suffix)
print(path.parent)
Output
notes.txt .txt .

Path('notes.txt') creates a Path object representing a relative path. path.name returns the final component, notes.txt. path.suffix returns .txt, including the dot. path.parent returns . because notes.txt has no directory component in this relative path. No file is created or opened by this example.

Note

Use pathlib for path manipulation, but remember that operations such as read_text(), write_text(), unlink(), and mkdir() interact with the filesystem and may fail because of missing files, permissions, or other environmental conditions.

6. The datetime module

The datetime module provides classes for representing dates and times. A date represents a calendar date, a time represents a time of day, and a datetime combines a date and a time.

You can construct a specific date or datetime explicitly, which makes examples and tests predictable. The strftime() method formats a date or time using format codes.

For example, %Y represents a four-digit year, %m represents a two-digit month, and %d represents a two-digit day. The exact format string determines how the result is displayed.

A datetime object does not automatically include a time zone unless it is configured as an aware datetime. For applications involving users in different locations, time zones and daylight-saving rules require additional care.

Create and format a date

Create and format a date
python
from datetime import date
 
birthday = date(2004, 5, 12)
print(birthday)
print(birthday.strftime('%d-%m-%Y'))
Output
2004-05-12 12-05-2004

date(2004, 5, 12) creates a date for May 12, 2004. Printing the date uses its standard ISO-style representation: YYYY-MM-DD. strftime('%d-%m-%Y') formats the same date as day-month-year. The date is fixed in the code, so this example does not depend on the current date.

7. Choosing the right module

The best module depends on the problem you need to solve. These modules are not interchangeable: math focuses on mathematical operations, statistics summarizes data, random generates pseudorandom values, pathlib handles filesystem paths, and datetime handles dates and times.

Choose a standard-library function that expresses your intention directly. For example, use statistics.median() rather than writing a custom sorting algorithm just to find a median, and use Path objects rather than manually combining directory and filename strings.

Before using an operation, check its expected input and return value. Also consider whether it depends on external conditions, such as the filesystem, current time, or pseudorandom state.

Match a task to a module

Match a task to a module
python
import math
import statistics
from pathlib import Path
from datetime import date
 
print(math.sqrt(81))
print(statistics.median([1, 9, 3]))
print(Path('report.pdf').suffix)
print(date(2026, 10, 12).year)
Output
9.0 3 .pdf 2026

math.sqrt() calculates a square root. statistics.median() finds the middle value of the supplied data. Path.suffix extracts the final extension from a path. date.year retrieves the year component from a date. Each statement uses a module whose purpose matches the task.

Caution

A standard-library function is not automatically suitable for every input. Empty datasets, invalid date components, empty sequences, missing files, and permission errors can produce exceptions. Learn the expected inputs and error behavior of the specific operation you use.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Assuming every standard-library module must be installed separately.

Why it happens: Modules such as math, statistics, pathlib, and datetime are included with standard Python distributions and usually do not need separate installation.

Incorrect Approach
script.py
python
Assuming every standard-library module must be installed separately.
Correct Solution
script.py
python
These five modules are included with Python. Third-party packages are separate and may require installation.

Key takeaway: These five modules are included with Python. Third-party packages are separate and may require installation.

#2 Using a function without importing its module or name.

Why it happens: Python names are not automatically available in the current namespace; import the module or the specific name before using it.

Incorrect Approach
script.py
python
Using a function without importing its module or name.
Correct Solution
script.py
python
Import the module first, then use module.function(), or explicitly import the function you want.

Key takeaway: Import the module first, then use module.function(), or explicitly import the function you want.

#3 Confusing mean and median.

Why it happens: The mean uses all values and is sensitive to extremes, while the median is the middle value or average of the two middle values after sorting.

Incorrect Approach
script.py
python
Confusing mean and median.
Correct Solution
script.py
python
Mean is the arithmetic average; median is the middle value after ordering the data, or the average of the two middle values.

Key takeaway: Mean is the arithmetic average; median is the middle value after ordering the data, or the average of the two middle values.

#4 Assuming random.randint(a, b) excludes b.

Why it happens: random.randint(a, b) includes both endpoints, so b is a possible result.

Incorrect Approach
script.py
python
Assuming random.randint(a, b) excludes b.
Correct Solution
script.py
python
randint includes both a and b.

Key takeaway: randint includes both a and b.

#5 Assuming Path('notes.txt') creates a file.

Why it happens: Path('notes.txt') represents a filesystem path; creating the Path object alone does not create the file.

Incorrect Approach
script.py
python
Assuming Path('notes.txt') creates a file.
Correct Solution
script.py
python
A Path object represents a path. Creating the object alone does not create or open the corresponding file.

Key takeaway: A Path object represents a path. Creating the object alone does not create or open the corresponding file.

#6 Confusing month and minute format codes.

Why it happens: Datetime formatting uses distinct directives for month and minute, such as %m for month and %M for minute.

Incorrect Approach
script.py
python
Confusing month and minute format codes.
Correct Solution
script.py
python
In datetime formatting, %m means month and %M means minute.

Key takeaway: In datetime formatting, %m means month and %M means minute.

#7 Using random for cryptographic secrets.

Why it happens: The random module is designed for simulations and general-purpose randomness, not unpredictable values needed for security.

Incorrect Approach
script.py
python
Using random for cryptographic secrets.
Correct Solution
script.py
python
Use secrets for security-sensitive random values.

Key takeaway: Use secrets for security-sensitive random values.

#8 Writing sqrt(25) after importing only math.

Why it happens: Importing only the math module binds the name math; call math.sqrt(25) or explicitly import sqrt.

Incorrect Approach
script.py
python
Writing sqrt(25) after importing only math.
Correct Solution
script.py
python
Use math.sqrt(25), or explicitly import the function with from math import sqrt before calling sqrt(25).

Key takeaway: Use math.sqrt(25), or explicitly import the function with from math import sqrt before calling sqrt(25).

#9 Assuming math.ceil() and math.floor() both round to the nearest integer.

Why it happens: ceil() rounds toward positive infinity and floor() toward negative infinity; neither is ordinary rounding to the nearest integer.

Incorrect Approach
script.py
python
Assuming math.ceil() and math.floor() both round to the nearest integer.
Correct Solution
script.py
python
ceil rounds toward positive infinity, while floor rounds toward negative infinity.

Key takeaway: ceil rounds toward positive infinity, while floor rounds toward negative infinity.

#10 Expecting randint(1, 6) to return only values from 1 through 5.

Why it happens: randint() includes the upper bound, so random.randint(1, 6) can return 6.

Incorrect Approach
script.py
python
Expecting randint(1, 6) to return only values from 1 through 5.
Correct Solution
script.py
python
Both endpoints are included, so 1 and 6 are valid results.

Key takeaway: Both endpoints are included, so 1 and 6 are valid results.

#11 Expecting every random call to return the same value.

Why it happens: Random results vary across calls unless controlled by a seed or another reproducibility mechanism; identical results should not be assumed.

Incorrect Approach
script.py
python
Expecting every random call to return the same value.
Correct Solution
script.py
python
Results can vary. For repeatable tests, seed the pseudorandom generator appropriately and avoid relying on an unseeded random output.

Key takeaway: Results can vary. For repeatable tests, seed the pseudorandom generator appropriately and avoid relying on an unseeded random output.

#12 Using random to generate security tokens.

Why it happens: Security tokens require cryptographically secure randomness, such as the secrets module, rather than random.

Incorrect Approach
script.py
python
Using random to generate security tokens.
Correct Solution
script.py
python
Use the secrets module when values must be difficult for an attacker to predict.

Key takeaway: Use the secrets module when values must be difficult for an attacker to predict.

#13 Using the wrong strftime format codes.

Why it happens: strftime() directives are specific codes; using the month code where a minute code is intended produces incorrect output.

Incorrect Approach
script.py
python
Using the wrong strftime format codes.
Correct Solution
script.py
python
Remember that %m is the month, %M is the minute, %d is the day, and %Y is the four-digit year.

Key takeaway: Remember that %m is the month, %M is the minute, %d is the day, and %Y is the four-digit year.

#14 Assuming a datetime object always represents a globally unambiguous moment.

Why it happens: A naive datetime lacks timezone information, so it may not identify one unique global instant without additional context.

Incorrect Approach
script.py
python
Assuming a datetime object always represents a globally unambiguous moment.
Correct Solution
script.py
python
A naive datetime has no time-zone information. Use time-zone-aware datetimes when the application needs to represent moments across time zones.

Key takeaway: A naive datetime has no time-zone information. Use time-zone-aware datetimes when the application needs to represent moments across time zones.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is the Python standard library, and why is it useful?
Answer:
The Python standard library is a collection of modules distributed with Python. It provides reusable functionality for common tasks, such as mathematical operations, statistics, filesystem paths, dates, and times, without requiring a separate third-party package for those features.
Q2:What is the difference between math and statistics?
Answer:
math provides mathematical functions and constants, such as sqrt(), ceil(), floor(), and pi. statistics provides functions for summarizing datasets, such as mean() and median().
Q3:What is the difference between random.randint() and random.random()?
Answer:
randint(a, b) returns an integer from a through b, including both endpoints. random() returns a floating-point value greater than or equal to 0.0 and less than 1.0.
Q4:Why use pathlib instead of manually manipulating path strings?
Answer:
pathlib provides a Path object with properties and methods for working with filesystem paths. It makes operations such as joining path components and retrieving a suffix clearer and helps avoid assumptions about path separators.
Q5:What is the difference between date and datetime?
Answer:
A date represents a calendar date, while a datetime represents a date together with a time of day. A datetime may also include time-zone information when constructed appropriately.
Q6:How would you verify a standard-library example?
Answer:
Check the function's documented behavior and input requirements, trace the code, predict the result, run it where possible, compare the actual output with the expected output, and test relevant boundary cases and exceptions.

Key takeaways

  • The standard library provides reusable modules distributed with Python.
  • Use math for mathematical functions and constants, and statistics for numerical summaries.
  • Use random for pseudorandom values, but use secrets for security-sensitive randomness.
  • Use pathlib.Path to represent and manipulate filesystem paths; constructing a Path object does not create a file.
  • Use datetime and date to represent dates and times, and strftime() to format them.
  • Check function inputs, return values, exceptions, and environment-dependent behavior instead of assuming every operation works for every input.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: