Learn Python
>>> modules_packages.import_modules

Importing Modules in Python

#concept

A module is simply a Python file containing code — functions, classes, variables — that other files can reuse with the import statement. Importing a module runs it once and gives access to everything it defines, without needing to copy and paste that code into every file that needs it.

#how it works
1

import module_name

Makes everything in that module accessible through module_name.thing.

2

from module_name import thing

Brings a specific function, class, or variable directly into the current file's namespace.

3

import module_name as alias

Gives the imported module a shorter or clearer local name.

4

The standard library ships ready to use

Modules like math, random, and datetime need no extra installation.

5

A module runs only once per program

No matter how many files import it — later imports just reuse what’s already loaded.

#example
import math
from math import pi
import datetime as dt
 
print(math.sqrt(16))
print(pi)
print(dt.date(2024, 1, 1).year)
Output
4.0
3.141592653589793
2024
1import math brings in the whole module, so its functions are accessed as math.sqrt(), math.pi, and so on.
2from math import pi brings just that one constant directly in, usable as pi without a prefix.
3import datetime as dt gives the module a shorter local name, so dt.date(...) is used instead of the full datetime.date(...).
4Each import style works identically in terms of what code actually runs — they only differ in how the imported names are referenced afterward.
#use cases
Using Python's vast standard library instead of writing common functionality (math, dates, random numbers) from scratch
Organizing a large program's code across multiple files, importing what's needed where it's needed
Renaming an imported module for brevity or to avoid a naming clash, using the as keyword
Bringing in just the specific functions actually needed from a large module, keeping code more explicit about its dependencies

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in Python yourself — building beats watching.