When your Python file needs code from another file or library, you use import.
| Read | Build | Watch | Test | Review | Visualize |
|---|---|---|---|---|---|
| You are here | Projects | Videos | Quiz | Flashcards | Diagrams |
See how Python searches for and loads modules when you import: Open in Python Tutor
import math
print(math.sqrt(16)) # 4.0from math import sqrt, pi
print(sqrt(16)) # 4.0 — no "math." prefix needed
print(pi) # 3.14159...If you have two files in the same folder:
my_project/
├── main.py
└── helpers.py
# helpers.py
def greet(name):
return f"Hello, {name}!"
# main.py
from helpers import greet
print(greet("Alice"))A package is a folder that contains Python files and an __init__.py:
my_package/
├── __init__.py # Makes this folder a package (can be empty)
├── calculator.py # A module
└── statistics.py # Another module
from my_package.calculator import add
from my_package import statistics__init__.py runs when you import the package. It controls what gets exported:
# my_package/__init__.py
from my_package.calculator import add, subtract
from my_package.statistics import mean
# Now users can do:
# from my_package import add, meanWithout __init__.py, Python does not recognize the folder as a package.
When you write import something, Python looks in this order:
- Current directory (the folder your script is in)
- Installed packages (
site-packages/— things you installed with pip) - Standard library (modules that come with Python, like
os,json,math)
You can see the full search path:
import sys
print(sys.path)Alias (rename on import):
import pandas as pd
import numpy as npImport everything (avoid this):
from math import * # Bad — pollutes your namespace, hard to track what came from whereConditional import:
try:
import ujson as json # Faster JSON library
except ImportError:
import json # Fall back to standard libraryCircular imports:
# file_a.py
from file_b import helper_b # file_b imports from file_a → circular!
# file_b.py
from file_a import helper_a # Fails with ImportErrorFix: restructure so both files import from a third file, or move imports inside functions.
Naming conflicts:
# Don't name your file "random.py" — it shadows the built-in random module!
import random # Imports YOUR random.py instead of Python'sMissing __init__.py:
# If my_package/ has no __init__.py:
from my_package import calculator # May fail in some Python versions- Module 11 Package Publishing
- Level 01 projects
- Level 0 / 15 Level0 Mini Toolkit
- Level 1 / 01 Input Validator Lab
- Level 1 / 02 Password Strength Checker
- Level 1 / 03 Unit Price Calculator
- Level 1 / 04 Log Line Parser
- Level 1 / 05 Csv First Reader
- Level 1 / 06 Simple Gradebook Engine
- Level 1 / 07 Date Difference Helper
- Level 1 / 08 Path Exists Checker
- Level 1 / 09 Json Settings Loader
Quick check: Take the quiz
Review: Flashcard decks Practice reps: Coding challenges
| ← Prev | Home | Next → |
|---|