Introduction
In this lesson, we'll explore the world of Python built-in libraries, which are powerful tools that come standard with Python and save time by providing ready-to-use functions and modules. We'll delve into some specific libraries such as math, datetime, os, shutil, and collections. By the end of this lesson, you'll be able to leverage these libraries to perform mathematical computations, manipulate dates, handle files, and work with specialized data structures in your Python programs.
Using the Math Library
The math library provides a suite of mathematical functions, constants, and calculations.
Basic Math Functions
Start by importing the math module:
import math
Here are some common functions:
# Calculate square root
print(math.sqrt(16)) # Output: 4.0
# Find the greatest common divisor
print(math.gcd(28, 35)) # Output: 7
# Use constants like pi and e
print(math.pi) # Output: 3.141592653589793
Working with Dates using the Datetime Library
Python's datetime library allows you to handle dates and times effectively.
from datetime import datetime, timedelta
# Get today's date
today = datetime.now()
print(today) # Outputs current date and time
# Adding days to the current date
future_date = today + timedelta(days=5)
print(future_date) # Outputs date five days from now
Formatting Dates
Convert dates to strings or parse strings to dates with formatting:
# Formatting date
formatted_date = today.strftime("%Y-%m-%d")
print(formatted_date) # Output: e.g., '2023-10-15'
# Parse string date
date_string = "2023-10-20"
date_object = datetime.strptime(date_string, "%Y-%m-%d")
print(date_object)
File Handling with OS and Shutil
The os library allows interaction with the operating system, including file management. shutil complements os by providing higher-level file operations.
Using OS for File Inspection
import os
# Check current working directory
print(os.getcwd())
# List files in a directory
print(os.listdir('.'))
File Operations with Shutil
import shutil
# Copy a file
shutil.copy('source.txt', 'destination.txt')
# Move a file
shutil.move('source.txt', 'new_directory/source.txt')
Enhancing Data Structures with Collections
The collections module expands upon Python's standard data types with additional, powerful data structures.
Using defaultdict
defaultdict lets you specify a default value type for a dictionary:
from collections import defaultdict
d = defaultdict(int)
d['a'] += 1
print(d['a']) # Output: 1
Leveraging Counter
Counter aids in counting hashable objects:
from collections import Counter
count = Counter("abracadabra")
print(count) # Output: {'a': 5, 'b': 2, 'r': 2, 'c': 1, 'd': 1}
Summary / Key Takeaways
In this lesson on Using Built-in Libraries, you have learned:
- The
mathlibrary provides essential mathematical functions and constants. - The
datetimelibrary is useful for manipulating and formatting date and time data. - The
oslibrary allows you to interact with the operating system for file and directory management. - The
shutillibrary aids in file operations such as copying and moving files. - The
collectionsmodule introduces powerful alternatives to standard data types with classes likedefaultdictandCounter.
