HomeCourseModule 05 › Modules and imports — using other people's code

Modules and imports — using other people's code

Module 05 · Functions7 min readBeginner

What you'll learn

  • Import a module
  • Use from-import for a specific function
  • Recognise the standard library vs pip-installed libraries

The three import styles

# 1 — the whole module
import math
math.sqrt(16)        # 4.0

# 2 — with an alias (the convention for big libraries)
import pandas as pd
pd.read_csv("file.csv")

# 3 — a specific name
from math import sqrt, pi
sqrt(16)             # 4.0
pi                   # 3.14159...

Standard library vs third party

The conventional aliases

LibraryConventional alias
pandasimport pandas as pd
numpyimport numpy as np
matplotlib.pyplotimport matplotlib.pyplot as plt
seabornimport seaborn as sns

Use the conventions. Strangers reading your code will thank you.

Writing your own module

Any .py file is automatically importable from a script in the same folder. Put related functions in helpers.py:

# helpers.py
def clean_email(s):
    return s.strip().lower()

Then in main.py next to it:

from helpers import clean_email
clean_email("  ALICE@example.com ")   # 'alice@example.com'

Key takeaways

  • import x / import x as y / from x import y — three styles.
  • Standard library = free; third-party = pip install.
  • Use the conventional aliases (pd, np, plt, sns).
  • Any of your own .py files is importable.

Use the standard library

Use the datetime module to print today's date in the format YYYY-MM-DD. Hint: from datetime import date; date.today().isoformat().

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.