Learn Without Walls
← Previous Lesson Lesson 2 of 4 Next Lesson →

Lesson 10.2: Import Statements

What you will learn:

1. The Basic import Statement

The simplest way to use a module is with the import keyword. This imports the entire module, and you access its contents using dot notation:

import math

# Use dot notation: module_name.function_name
result = math.sqrt(49)
print(result)           # 7.0
print(math.pi)          # 3.141592653589793
print(math.ceil(4.3))   # 5
7.0
3.141592653589793
5
Dot notation: The pattern module.function() that tells Python to look inside a specific module for a function or variable. Think of it like saying "from the math module, use the sqrt function."

The advantage of this approach is that it is very clear where each function comes from. When you see math.sqrt(), you immediately know it is from the math module.

2. The from...import Statement

If you only need specific functions from a module, you can import just those functions. This lets you use them without the module name prefix:

Importing Specific Functions

# Import only what you need
from math import sqrt, pi

# Now use them directly - no "math." needed
result = sqrt(64)
print(result)    # 8.0
print(pi)        # 3.141592653589793

# But other math functions are NOT available:
# print(ceil(4.3))  # NameError! ceil was not imported
8.0
3.141592653589793

Importing Multiple Items

from random import randint, choice, shuffle

# All three functions are directly available
print(randint(1, 10))
print(choice(["a", "b", "c"]))

names = ["Alice", "Bob", "Charlie"]
shuffle(names)
print(names)
7
b
['Charlie', 'Alice', 'Bob']
Warning about import *: You might see from math import * which imports everything. This is generally discouraged because it can cause naming conflicts and makes it unclear where functions come from. Stick to importing specific items.

3. Creating Aliases with import...as

Sometimes module names are long. You can create a shorter alias (nickname) using as:

Module Aliases

# Create a shorter name for a module
import datetime as dt

now = dt.datetime.now()
print(now.strftime("%Y-%m-%d"))

# Common aliases you'll see in Python code:
# import numpy as np        (data science)
# import pandas as pd       (data analysis)
# import matplotlib.pyplot as plt  (plotting)
2025-06-15

Function Aliases

# You can also alias specific imports
from math import sqrt as square_root
from random import randint as random_number

result = square_root(36)
print(result)  # 6.0

num = random_number(1, 100)
print(num)
6.0
42

4. Comparing Import Styles

Here is a side-by-side comparison of the three import styles:

Three Ways to Import

# Style 1: Import the whole module
import math
print(math.sqrt(16))    # Must use math.sqrt

# Style 2: Import specific items
from math import sqrt
print(sqrt(16))         # Use sqrt directly

# Style 3: Import with an alias
import math as m
print(m.sqrt(16))      # Use shorter alias
4.0
4.0
4.0
Style Best When Consideration
import mathUsing many functions from a moduleVery clear, but more typing
from math import sqrtUsing only a few specific functionsLess typing, but less clear origin
import math as mModule name is long or has a conventionGood balance of clarity and brevity

5. What Happens During Import

When Python encounters an import statement, several things happen behind the scenes:

  1. Python searches for the module in its list of known locations
  2. The module code runs once (Python executes the file)
  3. A module object is created that contains all the functions and variables
  4. The name is bound in your program so you can use it
Important: Python only runs a module's code once, even if you import it multiple times. The second import statement simply reuses the already-loaded module.

Import Order Convention

# Best practice: put all imports at the top of your file
# Group them in this order:

# 1. Standard library imports
import math
import random
from datetime import datetime

# 2. Third-party imports (installed with pip)
# import requests
# import pandas as pd

# 3. Your own modules
# from my_module import my_function

# Your code starts here
print("Program begins!")

Check Your Understanding

If you write from random import choice, can you later use random.randint(1, 10)?

No. When you use from random import choice, you only import the choice function, not the entire random module. To use randint, you would need to either add it to the import (from random import choice, randint) or import the whole module separately (import random).

Key Takeaways

← Previous Lesson Lesson 2 of 4 Next Lesson →