Bigger programs · lesson 7 of 12
Parts in this lesson
Aimport matha whole module
Bfrom x import yone name from it
Cfines.pyyour own module
D__name__which file is running
Edate + timedeltadates and days

Modules and the standard library

Last updated

Python comes with hundreds of ready-made modules: for maths, dates, random choices and much more. In this lesson you'll import them, split your own code into a second file, keep that file's test lines from running when it's imported, work out due dates, and read the error you get when an import is misspelt.

By the end of this lesson you can

  • Use import and from ... import to bring in a module from the standard library
  • Move functions into your own module and import them from another file
  • Guard a module's own test code with if __name__ == "__main__":
  • Work out due dates and days late with datetime

Bringing in a module

A module is a file of Python code that other programs can use. Python comes with hundreds of them, called the standard library: tools for maths, dates, random numbers, files and much more. None of them are loaded until you ask.

import math loads the math module. You then reach its names with a dot: math.ceil() rounds up, math.pi is π. from statistics import mean brings in just one name, so you can write mean(...) without the module's name in front.

Step 1 code main.py
Edit the code, then run it again

Imports go at the top of the file, one per line, so a reader sees straight away what the program uses. Use import math when you'll use several of its names, since math.ceil says where ceil came from. Use from ... import for one or two names you use a lot. You can also rename as you import, import statistics as stats, but use that sparingly.

Your own module

Any .py file is a module, including yours. This step has two files: click the fines.py tab to see the second one. It holds the fine rules from the Stage 1 project. main.py imports it by its name, without the .py, and calls its function with a dot, just like math.ceil.

Step 2 code
Edit the code, then run it again

Change MAX_FINE in fines.py to 300, then run main.py again. Every program that imports fines now gets the new rule. That's the point of a module: one place for code that several programs share. The text in triple quotes at the top of fines.py is a docstring, a note saying what the module is for.

For Python to find fines.py, it has to be in the same folder as the program that imports it. Here the page puts both files in one folder for you.

Run, or imported?

While you write fines.py you'll want to try it out, so you add a few lines at the bottom that call it. But those lines also run when another program imports the module. Press Run and look at the first two lines of output:

Step 3 code
Edit the code, then run it again

main.py only asked for one fine, yet Trying fine_for: and 50 appeared too. Importing a module runs the whole file, top to bottom.

Python gives every module a name, __name__ (two underscores each side). The file you run is called "__main__"; a module that's imported is called by its file name, here "fines". So the test lines go under if __name__ == "__main__":. They run when you run fines.py itself, and are skipped when it's imported:

Step 3 code
Edit the code, then run it again

You'll see this if at the bottom of many Python files. It means "this file can be run as a program, and imported as a module".

Due dates

The datetime module knows the calendar: months of different lengths, leap years, days of the week. date(2026, 12, 4) is one day. A timedelta is a length of time, so adding timedelta(days=14) to a date gives the date two weeks later. Taking one date from another gives a timedelta, and its .days is the number of days between them.

Step 4 code main.py
Edit the code, then run it again

Line 7 formats the date in an f-string: after the colon, %A is the day's name, %d the day of the month and %B the month's name. A real library would start from today with date.today(). These examples use fixed dates so you get the same output every time.

Random choices

The random module makes choices: random.choice() picks an item from a list, random.randint(1, 6) gives a whole number from 1 to 6, both ends included, and random.shuffle() mixes a list into a new order.

Step 5 code main.py
Edit the code, then run it again

Line 3 sets a seed. Random numbers on a computer come from a calculation, and the seed is where it starts, so the same seed always gives the same "random" results. That's handy here and in tests. Delete line 3 and run it a few times to see the choices change.

Don't name your own file after a module you use. A file called random.py beside your program would be imported instead of Python's, and random.choice would stop with an AttributeError.

A typo in an import

Press Run and read the error.

Step 6 code main.py
Edit the code, then run it again

ModuleNotFoundError: No module named 'datetiem'. Python looked in the program's folder and in the standard library, and found no module by that name. Fix the spelling on line 2. Then you'll notice line 2 isn't needed at all, since line 1 already imports what the program uses, so delete it.

The same error appears when a module isn't installed. In lesson 2.9 you'll install modules other people have written.

Check what you learned

Four questions. Pick or type an answer, then check it.

What does this program print?
from datetime import date, timedelta

due = date(2026, 12, 4) + timedelta(days=7)
print(due.day)
After from math import ceil, how do you call ceil?
fines.py ends with if __name__ == "__main__": and two print lines under it. When do those lines run?
Why use random.seed(1) in an example?

Sources

Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.

All sources for Simple Python