Python Modules
Core Python Functions and Modules

Python Modules and Imports

1Python Modules: overview

A module is a file of Python code (functions, classes and values) that you load into your program with import, so you can reuse it instead of writing it again.

GoalBy the end you can import a module in three ways (import, from … import, as), use math, random, datetime and collections, split your own code into a module, and explain what if name == "main" does.

Before this lesson: Python Functions, Python Variable Scope

2Python Modules: diagram

Python Modules and Importsmain.pyyour scriptimport mathfind the modulefoundmath moduleruns once, cachedloadedmath.sqrt(16)use name.function
When your script runs import math, Python finds the math module, runs it once and gives you the name math. You then reach everything inside it with a dot, like math.sqrt(16).

3Python Modules: explained step by step

A module is a file of Python code that another program can load and use. Python comes with hundreds of them, together called the standard library, and every .py file you write is a module too. Importing lets you reuse code that already exists instead of writing it again, and it lets you split a big program into tidy, separate files.

Three ways to import

Python
import math                       # the whole module
from random import choice, seed   # only the names you need
import datetime as dt             # the module under a short nickname

print(math.sqrt(81))
seed(1)
print(choice(["red", "green", "blue"]))
print(dt.date(2025, 3, 15).year)

  • import math keeps the module name as a prefix, so you write math.sqrt(). It takes a few more keystrokes, but anyone reading the code can see exactly where sqrt came from.
  • from random import choice copies choice straight into your file, so you call it without a prefix. That's handy for names you use a lot, but if you also define your own choice, one silently replaces the other.
  • as gives a module a nickname. You will see import numpy as np and import pandas as pd in almost every data project.

A quick tour of the standard library

  • math: square roots, rounding up and down (ceil, floor), pi.
  • random: random numbers and choices. Call random.seed(n) first when you need the same "random" results on every run, for example in tests.
  • datetime: dates, times and the gaps between them (timedelta).
  • collections: smarter containers such as Counter and defaultdict.
Python
from collections import Counter
from datetime import date

votes = ["tea", "coffee", "tea", "juice", "tea"]
print(Counter(votes).most_common(2))

start = date(2025, 1, 1)
deadline = date(2025, 3, 1)
print((deadline - start).days, "days to go")

Writing your own module

Save a few functions in a file called helpers.py:

# helpers.py
TAX_RATE = 0.2

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

Any file in the same folder can now import it. Use the file name without .py:

# main.py
import helpers

print(helpers.add_tax(50))   # 60.0

Snippets on this page run as a single file, so they can only import built-in modules. The site's IDE lets you create several files: make a helpers.py there and import it from main.py to try this for real.

What if __name__ == "__main__" means

Importing a module runs all of its top-level code once. Python also gives every module a special variable, __name__. In the file you actually ran it is "__main__"; in a file that was imported it is the module's own name, such as "helpers". So code inside if __name__ == "__main__": runs only when you run that file directly. It's the right place for demos and quick tests that should stay quiet when someone imports your module.

Python
def area(width, height):
    return width * height

print("__name__ is", __name__)

if __name__ == "__main__":
    print("Run directly, testing:", area(3, 4))

Quick reference: Python Modules

4Python Modules: syntax

import module_name                    # use as module_name.thing
import module_name as alias           # use as alias.thing
from module_name import name1, name2  # use name1 directly

if __name__ == "__main__":
    # runs only when this file is run directly, not when imported
    main()

5Python Modules: run the example

Press Run (or Ctrl + Enter). The output (step 6) appears directly below the code. Change anything and run it again.

Interactive example
import math
import random
from datetime import date, timedelta
from collections import Counter

students = 27
seats_per_bus = 12
buses = math.ceil(students / seats_per_bus)
print("Buses needed:", buses)

trip_day = date(2025, 5, 12)
reminder = trip_day - timedelta(days=7)
print("Send reminder on:", reminder.strftime("%A, %d %B %Y"))

random.seed(42)
leader = random.choice(["Asha", "Ben", "Chen", "Dara"])
print("Trip leader:", leader)

lunches = ["veg", "chicken", "veg", "fish", "veg", "chicken"]
print("Lunch orders:", Counter(lunches).most_common())
Expected outputBuses needed: 3
Send reminder on: Monday, 05 May 2025
Trip leader: Asha
Lunch orders: [('veg', 3), ('chicken', 2), ('fish', 1)]

7Python Modules: how the example works

Hover or tap a step to highlight its lines in the example above.

  1. Line 1-4Two import styles: math and random are imported whole (used with a prefix), while date, timedelta and Counter are pulled out of their modules by name.
  2. Line 6-927 / 12 is 2.25, and you can't book a quarter of a bus. math.ceil() rounds up to the next whole number: 3.
  3. Line 11-13date(2025, 5, 12) is a fixed date. Subtracting a timedelta of 7 days gives 5 May, and strftime() formats it with the weekday (%A) and month name (%B).
  4. Line 15-17random.seed(42) fixes the starting point of the random number generator, so choice() picks the same leader on every run. Remove the seed and the leader changes each time.
  5. Line 19-20Counter counts how often each value appears, and most_common() lists them from most to least frequent.

8Python Modules: common mistakes

Naming your own file after a module you import

✗ Wrong

# this file is saved as random.py
import random

print(random.randint(1, 6))
AttributeError: module 'random' has no attribute 'randint' (consider renaming 'random.py' since it has the same name as the standard library module ...)

✓ Right

# this file is saved as dice.py
import random

print(random.randint(1, 6))

Python looks in your own folder first, so import random loaded your file instead of the real module. Give your file a different name, such as dice.py.

Calling a function without its module name

✗ Wrong

import math

print(sqrt(49))
NameError: name 'sqrt' is not defined

✓ Right

import math

print(math.sqrt(49))

import math creates only the name math. Either write math.sqrt(49), or import the function itself with from math import sqrt.

Mixing up the datetime module and the datetime class

✗ Wrong

import datetime

meeting = datetime(2025, 6, 1, 9, 30)
TypeError: 'module' object is not callable. Did you mean: 'datetime.datetime(...)'?

✓ Right

from datetime import datetime

meeting = datetime(2025, 6, 1, 9, 30)
print(meeting)

The module and the class inside it are both called datetime. Import the class with from datetime import datetime, or write datetime.datetime(...).

9Python Modules: exercises

Write your answer, then press Check. The checks run in your browser.

1. How many boxes?

Write code Easy

Complete the function boxes_needed(items, per_box) so it returns how many boxes are needed to pack items things when each box holds per_box. A part-full box still counts, so round up with the math module. For example boxes_needed(10, 4) is 3.

Your code
import math

def boxes_needed(items, per_box):
    # return the number of boxes (round up!)
    pass

print(boxes_needed(10, 4))

2. Predict the imports

Predict the output Medium

Read the code and type exactly what it will print. Then press Check to run it and compare.

Read this code
import math as m
from collections import Counter

print(m.floor(7.9), m.ceil(7.1))
print(Counter("banana")["a"])
print(__name__)

2 more exercises → 4 more examples

Finished this lesson?
Progress is saved in this browser — create a free account to keep it across devices.

Questions learners ask

What is the difference between a module and a package in Python?

A module is a single .py file. A package is a folder that groups several modules (and sometimes smaller packages) under one name. You reach the parts with dots, for example from email.message import EmailMessage or import xml.etree.ElementTree as ET. Both are imported with the same import statements.

Why does importing my file run its code?

To create a module's functions and variables, Python runs the module's top-level code the first time it is imported. Any print() calls or tests at the top level run too. Put that code under if name == "main": so it only runs when you run the file directly. Python also caches imports, so importing the same module again does not run it a second time.

Which modules can I import on this site?

Most of the standard library works, including math, random, datetime, json, csv, re, collections, itertools and statistics. Packages listed on the Packages page, such as numpy, pandas and matplotlib, load automatically when you import them. GUI modules like tkinter and turtle cannot run inside a browser.

Further reading

10Next lesson

Up nextPython math and statisticsPython's built-in operators, the math module and the statistics module handle everyday calculations such as roots, roun…

Related:
Python Variable ScopePython math and statisticsPython random ModulePython datetime Module

← Python Type Hints · All Functions and Modules lessons · Practise in the IDE