CodeMIRAI
0 XP

Modules and import

2 min read 5 runnable examples Quiz included

A module is a file of Python code you can reuse. Python ships with hundreds of them, the standard library, and thousands more can be installed.

import

Python
import math

print(math.sqrt(81))
print(math.pi)
print(math.ceil(4.2), math.floor(4.8))

import math loads the module; you then reach its contents with a dot: math.sqrt.

from ... import

Import specific names to use them without the module prefix:

Python
from math import sqrt, pi

print(sqrt(16), pi)

Aliases

as gives a module or name a shorter name. Some aliases are universal conventions:

Python
import statistics as stats
from datetime import date as Date

print(stats.mean([4, 8, 15, 16, 23, 42]))
print(Date(2026, 1, 1).strftime("%A"))

You'll see import numpy as np and import pandas as pd in every data-science script.

What's inside a module?

Python
import random

print([name for name in dir(random) if not name.startswith("_")][:15])
print(random.choice.__doc__.splitlines()[0])

dir() lists a module's names and help(module.name) shows its documentation.

Your own modules

Any .py file is a module. If you had a file shop.py containing:

Python
TAX_RATE = 0.18

def with_tax(price):
    return round(price * (1 + TAX_RATE), 2)

then another file in the same folder could use it:

Python
import shop
print(shop.with_tax(100))     # 118.0

if __name__ == "__main__"

A file's code runs when it is imported. To have code that runs only when the file is executed directly, not when imported, use this guard:

Python
def main():
    print("Running as a script")

if __name__ == "__main__":
    main()

Packages and pip

  • A package is a folder of modules.
  • pip installs packages from PyPI, the Python Package Index: pip install requests.

On CodeMIRAI, popular data packages (NumPy, pandas, matplotlib) load automatically when you import them.

Finished this lesson?Mark it complete to earn +20 XP and move your progress on.