Using Libraries

Imports, Names, and Documentation


Learning Objectives

  • You can use import module, from module import name, and common aliases.
  • You can explain why names from imported modules live in namespaces.
  • You can diagnose simple NameError and ModuleNotFoundError cases.
  • You can read a small documentation example and adapt it carefully.

An import statement makes names from another module available to your program. The most explicit form is:

import math
print(math.sqrt(64))

This imports the module as the name math. The function is then called as math.sqrt(...), which says exactly where sqrt came from.

The dot matters. It is Python’s way of looking inside the namespace of the module. A namespace is a place where names live. Your script has its own names. The math module has its names. math.sqrt means “the name sqrt inside math.”

Namespace lookup

0 / 5 points

After this import, which call is correct?

import math

Importing One Name

Sometimes you import just one name:

from math import sqrt
print(sqrt(64))

Now sqrt is available directly. This is shorter, but it hides where the name came from once the program grows. Both forms are valid. In beginner code, import math is often clearer because every call keeps the module name visible.

There is one form you should avoid in this course:

from math import *

This imports many names directly into your script. It is convenient for quick experiments, but it makes code harder to read because the source of each name becomes unclear.

Imported name

0 / 5 points

After this import, which call is correct?

from math import sqrt

Aliases

Some libraries have conventional aliases:

import numpy as np
import pandas as pd

The alias is just another name. After import pandas as pd, the name pd refers to the pandas package:

import pandas as pd
sessions = pd.DataFrame([
{"subject": "math", "minutes": 45},
{"subject": "history", "minutes": 30},
])
print(sessions)

You do not need to understand DataFrame yet. In this chapter, the important part is the name: pd.DataFrame(...) uses the pd alias to reach something inside pandas. Pandas DataFrames: Tables in Python introduces DataFrames as pandas tables.

The aliases np and pd are common enough that using them makes your code easier for other Python programmers to recognize. This is one of the few places where short names improve readability rather than harm it.

Pandas alias

0 / 5 points

What does import pandas as pd make available in the file?

Common Import Errors

Two errors come up often.

NameError means Python does not know a name:

print(math.sqrt(9)) # NameError if math was never imported

The fix is to import the module or use the name you actually imported.

ModuleNotFoundError means Python cannot find the module:

import pandas # ModuleNotFoundError if pandas is not installed

The fix depends on the module. If you mistyped a standard-library module, correct the spelling. If the module is third-party, install it into the Python environment you are using.

Missing module

0 / 5 points

What does ModuleNotFoundError: No module named 'pandas' usually mean in this course?

Name Collisions and Shadowing

Because imports create names, you can accidentally hide them. This is called shadowing: a new name in your file covers an older meaning of the same name.

import random
random = "math"
print(random.choice(["math", "history"])) # AttributeError

The import was fine. The bug is that the variable assignment reused the name random, so random no longer refers to the module. It now refers to a string.

The same problem can happen with filenames. If you create your own file called random.py, then write import random in the same folder, Python may import your file instead of the standard-library module. The error messages from this kind of bug can feel strange because the import name is correct but the imported thing is not the one you meant.

Good habits prevent most of this:

  • Do not name your own files random.py, math.py, csv.py, json.py, datetime.py, pandas.py, or numpy.py.
  • Do not reuse module names as ordinary variables.
  • If an import behaves strangely, print the value or type you imported in a tiny file.
import random
print(random)
print(type(random))

This is not a normal thing to leave in a finished program. It is a debugging move to check what Python thinks the name means.

Reading Documentation Examples

Library documentation often gives examples before it gives explanations. Read examples actively.

Suppose you see:

from datetime import date
d = date.fromisoformat("2019-12-04")

Ask:

  1. What was imported?
  2. What name is being called?
  3. What argument shape does it expect?
  4. What kind of value seems to come back?
  5. What can I change in a tiny experiment?

Then adapt only one thing at a time:

from datetime import date
session_day = date.fromisoformat("2026-05-10")
print(session_day)
print(session_day.year)
print(type(session_day.year))

Do not paste a large documentation example directly into your project and hope it fits. First shrink it, run it, and name the parts you understand.

Read a documentation example

0 / 5 points

Arrange the lines into a tiny experiment that adapts a datetime documentation example. In addition to printing the date and its year, the adaptation checks the type of the year value.

Copying Examples Carefully

Documentation examples often use placeholder names:

df = pd.DataFrame(data)

This is another preview of pandas table code. The important point here is not the DataFrame itself, but the habit of checking what names an example assumes.

In your program, there may be no name called data. Your study log might have a StudyLog object called log, with session objects in log.sessions. Adapting an example is not only copying the line. It means matching the example’s assumptions to your program’s names and data shape.

A careful adaptation might look like this:

log = load_study_log("sessions.json")
records = []
for session in log.sessions:
records.append(session.to_dict())
df = pd.DataFrame(records)

If the example uses a column called "duration" but your project uses "minutes", change the column name deliberately. If the example reads from a CSV file but your project already has a StudyLog loaded from JSON, start from the data you already have and convert it at the boundary where pandas needs table-shaped records.

The question is not “How do I paste this example?” The question is “Which part of this example is the library idea, and which part is just the example’s local setup?”

Import Style in This Part

This part will use:

import math
import random
from datetime import date, timedelta
import numpy as np
import pandas as pd

These are not the only valid forms, but using one consistent style makes the examples easier to compare. When you later read other code, you will see variations. The question to ask is always the same: what name is available in this file, and where did it come from?

Check Your Understanding

  1. What is the difference between import math and from math import sqrt?
  2. Why does math.sqrt(9) fail if the program only has from math import sqrt?
  3. Why are np and pd acceptable short names?
  4. What should you do before adapting a documentation example into your own project?

AI Study Aid

Create a chapter diagram

We're looking into to what extent AI-generated diagrams could help with studying.

Use this study aid to generate an AI-generated visual summary of the material you just studied. Each diagram style emphasizes the content in a different way, so you can choose the focus that feels most useful.

Using the diagram generator is voluntary and does not affect your course progress. We encourage you to try it out and see if it helps, but it's totally up to you! Your answers help us understand how to make better study aids in the future.

Diagrams tried: 0