Python, from Zero, for AILesson 26 of 89

Module 3 · Functions, modules, and code you can read again in March

Modules: splitting a script across files without breaking it

In this lesson

  • 8 min read
  • 6 reading sections
  • Knowledge check
  • Lesson 6 of 9 in this chapter

This chapter’s goalSplit a working script into functions and modules with explicit arguments, return values and docstrings, explain from Python’s scoping rules why a variable changed inside a function did or did not change outside it, and run the result from a terminal with named options.

This chapter’s media

The film explains chapter ideas. The audiobook narrates the complete teaching text.

FormatEnglishहिंदी
Chapter filmWatch1:44Not available
Full audiobookNot availableNot available

A little at a time

Explore an idea, try it, then check what stays.

Step 1 of 8Free · no account needed
Lesson steps

Every .py file is already a module

Put this in money.py:

Python
TAX_RATE = 0.18

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

And in main.py, in the same folder:

Python
import money

print(money.with_tax(100))     # 118.0

That is the whole mechanism. No registration, no build step. The file name without .py is the module name.

Three ways to bring things in:

Python
import money                       # money.with_tax(...)
from money import with_tax         # with_tax(...)
import money as m                  # m.with_tax(...)

The first keeps the source of the name visible at every call, which is worth more than the characters it costs. The second is fine for a handful of names you use constantly. Avoid from money import *: it dumps every public name into your file, so nobody can tell where anything came from, and a new name in money can silently shadow one of yours.

Your place and first choices stay on this browser. Classroom credit is recorded separately.

Stuck on something?Ask Divya, your AI tutor

How to cite: Addaly (2026) ‘Modules: splitting a script across files without breaking it’, in Python, from Zero, for AI. Edited by M. Mun. Addaly. Available at: https://addaly.com/learn/python-for-ai/modules-and-imports (Accessed: 29 November 2026).