01 / 21

Importing
Modules in Python

Learn how to import modules and functions using import and from statements to unlock Python's powerful standard library and beyond.

Python

What is a Module?

A module is simply a Python file (ending in .py) that contains definitions: functions, variables, and classes. Modules let you organize code into reusable pieces instead of writing everything in one giant file.

Why Import Modules?

Reusability
Write code once, use it in many programs without copy-pasting.
Organization
Split large programs into smaller, manageable files by topic.
Power
Access thousands of built-in and third-party tools: math, web, data, AI.

The Module Ecosystem

Your Script Standard Library math, os, random, json... Your Modules helpers.py, utils.py Third-Party requests, numpy... Program Output Results, files, web...

Your script can pull from three sources: Python's built-in standard library, your own .py files, or third-party packages installed via pip.

The import Statement

import math

result = math.sqrt(144)
print(result) # 12.0

The from...import Statement

from math import sqrt, pi

result = sqrt(144) # No prefix needed!
print(pi) # 3.141592653589793

This is ideal when you only need a few specific functions and want shorter, cleaner code.

import vs from...import

import math from math import sqrt
What's loaded Entire module Only specified names
Usage syntax math.sqrt() sqrt()
Name collisions Protected by prefix Possible if names overlap
Readability Clear origin of functions Shorter, cleaner calls
Best for Using many functions Using a few functions

Aliasing with as

import math as m

print(m.sqrt(64)) # 8.0
print(m.pi) # 3.14159...
from math import factorial as fact

print(fact(5)) # 120

The Wildcard Import: *

from math import * # Imports EVERYTHING

print(sqrt(25)) # 5.0
print(cos(0)) # 1.0
print(pi) # 3.14159...

The wildcard import is acceptable for quick experiments in the interactive shell, but should be avoided in scripts and production code.

How Importing Works

Step 1 Find the module Step 2 Compile to bytecode Step 3 Execute code Python's Search Order (sys.path): 1. Current directory → 2. PYTHONPATH → 3. Standard library → 4. Site-packages Caching: Python caches modules after first import: re-importing is instant.

Step-by-Step: How to Import

1
Identify what you need. Determine which functions or constants your program requires.
2
Choose the right syntax. Use import module for many functions, or from module import name for a few.
3
Place imports at the top. Convention requires all import statements at the very beginning of your file.
4
Use the imported names. Call functions with the correct prefix (or directly if using from).
5
Alias if needed. Use as to shorten long names for convenience and readability.

Example 1: The random Module

import random

# Random integer between 1 and 6
dice = random.randint(1, 6)
print("You rolled:", dice)

# Pick a random item from a list
colors = ["red", "blue", "green"]
pick = random.choice(colors)
print("Random color:", pick)

Example 2: from datetime import

from datetime import date, timedelta

today = date.today()
print("Today:", today)

next_week = today + timedelta(days=7)
print("Next week:", next_week)

Example 3: Combining Techniques

import os
from math import ceil, floor
import json as j

# Full import: prefix required
print(os.getcwd())

# Selective import: no prefix
print(ceil(4.2)) # 5
print(floor(4.8)) # 4

# Aliased import: use alias
data = j.dumps({"name": "Alice"})

Common Mistakes to Avoid

✕ Forgetting the Prefix
Writing sqrt(16) after import math causes a NameError. You need math.sqrt(16).
✕ Using import *
Wildcard imports pollute your namespace and make debugging harder. Be explicit about what you import.
✕ Circular Imports
Module A imports B, and B imports A. This creates an infinite loop. Restructure your code to avoid it.
✕ Wrong Module Name
Naming your file math.py shadows the built-in math module. Avoid naming files after standard library modules.

Import Syntax Summary

Syntax Usage Example Call
import math Full module math.sqrt(9)
from math import sqrt Specific name sqrt(9)
import math as m Aliased module m.sqrt(9)
from math import sqrt as s Aliased name s(9)
from math import * Everything (avoid!) sqrt(9)

Question 1 of 5

After writing import random, which of the following correctly generates a random integer between 1 and 10?

Question 2 of 5

What does the following code do?
from os import getcwd

Question 3 of 5

Which statement correctly creates an alias np for the module numpy?

Question 4 of 5

Why is from math import * generally discouraged in production code?

Question 5 of 5

You have a file called helpers.py with a function greet(). Which import lets you call greet() directly without a prefix?