Part 7: Libraries

Kerry Back, Rice University

Why Libraries?

Python’s power comes from its libraries - collections of pre-written code for specific tasks.

  • Built-in libraries: math, datetime, random
  • Third-party libraries: pandas, numpy, matplotlib

Libraries save time and provide tested, optimized solutions to common problems.

Importing from Libraries

Import specific functions from a library:

from math import sqrt

result = sqrt(9)
print(result)
3.0

Use the function directly without a prefix.

Practice: Importing Functions

Exercise 1 (with Gemini): Ask Gemini to “write Python code that imports the sqrt function from math and uses it”

Exercise 2 (on your own): Type from math import pi then print(pi) and run it.

Importing Entire Libraries

Import the whole library and access its contents:

import math

result = math.sqrt(9)
print(f"Square root: {result}")
print(f"Pi: {math.pi}")
print(f"Cosine of 0: {math.cos(0)}")
Square root: 3.0
Pi: 3.141592653589793
Cosine of 0: 1.0

Use library.function() syntax.

Practice: Importing Libraries

Exercise 1 (with Gemini): Ask Gemini to “write Python code that imports the math library and calculates the square root of 16”

Exercise 2 (on your own): Type import math then print(math.sqrt(25)) and run it.

Using Aliases

Abbreviate library names with as:

import math as m

result = m.sqrt(16)
print(result)
4.0

Especially useful for libraries with long names!

Practice: Using Aliases

Exercise 1 (with Gemini): Ask Gemini to “write Python code that imports math as m and uses it to calculate pi times 2”

Exercise 2 (on your own): Type import math as m then print(m.pi) and run it.

Standard Alias Conventions

These conventions are universally used:

import pandas as pd              # Data manipulation
import numpy as np               # Numerical arrays
import matplotlib.pyplot as plt  # Plotting
import seaborn as sns            # Statistical plotting
import statsmodels.api as sm     # Statistics

Important: AI tools like Gemini understand these conventions!

If you ask about pd.DataFrame, it knows you mean pandas.

Import Patterns Comparison

Three common patterns:

# 1. Import entire module
import math
x = math.sqrt(25)

# 2. Import with alias
import math as m
y = m.sqrt(25)

# 3. Import specific functions
from math import sqrt
z = sqrt(25)

print(f"All equal: {x == y == z}")
All equal: True

Practice: Import Patterns

Exercise 1 (with Gemini): Ask Gemini to “explain the difference between ‘import math’ and ‘from math import sqrt’”

Exercise 2 (on your own): Type import math then from math import pi then print(math.sqrt(9), pi) and run it.

Installing Libraries with pip

Use pip to install third-party libraries:

# Install a library
!pip install yfinance

# Install specific version
!pip install yfinance==0.2.50

# Upgrade to latest
!pip install --upgrade yfinance

# Check installed packages
!pip list

Note: In Colab, use !pip. In a terminal, use pip without !.

Common Libraries You’ll Use

Data Science: - pandas - data manipulation - numpy - numerical computing - scipy - scientific computing

Visualization: - matplotlib - basic plotting - seaborn - statistical plots - plotly - interactive plots

Finance: - yfinance - stock data - pandas-datareader - financial data

Example: Using Multiple Libraries

import math
from datetime import date, timedelta

# Use math
circle_area = math.pi * (5 ** 2)
print(f"Circle area: {circle_area:.2f}")

# Use datetime
today = date.today()
next_week = today + timedelta(weeks=1)
print(f"Today: {today}")
print(f"Next week: {next_week}")
Circle area: 78.54
Today: 2025-11-30
Next week: 2025-12-07

Practice: Multiple Libraries

Exercise 1 (with Gemini): Ask Gemini to “write Python code that imports and uses both math and datetime libraries”

Exercise 2 (on your own): Type import math then from datetime import date then print(math.pi, date.today()) and run it.

Summary

  • Libraries extend Python with specialized functionality
  • Import entire libraries: import math
  • Import specific functions: from math import sqrt
  • Aliases abbreviate names: import pandas as pd
  • Standard conventions: pd, np, plt, sns, sm
  • pip installs third-party libraries
  • Libraries make Python powerful for data science, finance, and more!

Next: We’ll use pandas for data manipulation!