Focused practice · 8 min read

Python Import Exercises: Modules, Aliases, and the Standard Library

Imports are a small piece of syntax with a large payoff: they let you use tested code instead of rebuilding every tool. The key is to make the source of each name obvious.

Import a module, then use its namespace

import math loads the module once and exposes its names through the math object. Prefixing a function with the module name tells the reader where it came from. It also keeps your own variables from colliding with library names.

import math
print(math.sqrt(81))
print(math.pi)

A module namespace

Bring one name into scope

from statistics import mean makes mean available directly. This is concise when the name is unambiguous. Import several names with a comma, but keep the list short enough to scan.

from statistics import mean, median
scores = [7, 9, 10]
print(mean(scores))
print(median(scores))

A focused from-import

Use an alias when it improves readability

An alias does not copy or rename the module on disk. It simply gives you another name in the current file. Short aliases are common for long module names, but avoid cryptic names that make the code harder to read.

import random as rnd
rnd.seed(7)
print(rnd.choice(["latte", "tea", "mocha"]))

One short alias

Explore the standard library

Before writing a helper, check whether the standard library already has it. math handles common numeric operations, statistics handles summaries, and re handles text patterns. Reading the official documentation is part of learning the language.

import math
print(math.gcd(12, 18))
print(math.factorial(5))

Useful functions you do not have to write

Avoid wildcard imports

from module import * hides where names came from and can silently replace a name you already use. Prefer import module or a short from-import list. Explicit imports are easier to search, test, and explain.

from math import ceil, floor
print(ceil(2.1))
print(floor(2.9))

Explicit is easier to follow

Your practice checklist

Common questions

What is the difference between import math and from math import sqrt?

import math loads the module and requires math.sqrt. from math import sqrt brings sqrt into the current namespace, so you call sqrt directly.

Are imports slow?

Python caches modules after the first import, so later imports are cheap. Importing a large third-party package can still take time at startup.

Should I use import *?

Usually no. It hides the source of names and can overwrite existing variables. Explicit imports are easier to understand and maintain.

Practice imports

12 questions on modules, from-import, aliases, math, and statistics.

Open practice

Keep reading: