9.4 Useful Standard Library Modules
Overview of some of the most useful modules that come pre-installed with Python, such as math, random, datetime, os, and sys.
Python has an extensive "Standard Library," which is a collection of modules available in every Python installation without needing to install them with pip. These modules provide tools for a wide range of common tasks, from mathematical calculations to interacting with the operating system.
math: Mathematical Functions
Provides access to advanced mathematical functions and constants beyond basic arithmetic operations.
import math
print(f"The value of pi: {math.pi}")
print(f"Square root of 81: {math.sqrt(81)}")
print(f"Ceiling of 4.3: {math.ceil(4.3)}")
print(f"Floor of 4.8: {math.floor(4.8)}")
random: Random Numbers and Choices
Used for generating random numbers, randomly selecting items from a list, or shuffling a list.
import random
print(f"Random integer (1-100): {random.randint(1, 100)}")
print(f"Random choice: {random.choice(['a', 'b', 'c'])}")
my_list = [1, 2, 3, 4, 5]
random.shuffle(my_list)
print(f"Shuffled list: {my_list}")
datetime: Handling Dates and Times
Provides classes for handling dates, times, and time intervals.
import datetime
now = datetime.datetime.now()
print(f"Now: {now.strftime('%d/%m/%Y %H:%M:%S')}")
tomorrow = now + datetime.timedelta(days=1)
print(f"Tomorrow will be: {tomorrow.day}/{tomorrow.month}")
os: Interacting with the Operating System
Provides a way to use operating system-dependent functionality, such as reading and writing files, managing directories (folders), and accessing environment variables. Its functionality in the live editor is limited for security reasons.
# import os
# print(f"Current directory: {os.getcwd()}")
# os.mkdir("new_folder")
sys: System Parameters and Functions
Provides access to variables and functions that interact closely with the Python interpreter, such as command-line arguments (`sys.argv`) and the Python version.
import sys
print(f"Python version: {sys.version}")
print(f"Platform: {sys.platform}")
Practical Exercises
Explore More with AI
Use AI to generate new examples, delve deeper into theory, or get your questions answered.