CHAPTER 19 · BEGINNER4 min read

Modules and imports

Use the standard library and organize your own functions into files that can be imported safely.

Python 3.12+Free to readModule 4 of 13
YOUR NEXT SMALL WINS

By the end, you’ll be able to…

  • Import a module and access its names through a namespace.
  • Distinguish import styles and avoid names that shadow standard modules.
  • Create a two-file program with an explicit main guard.

01A module is a reusable namespace

A module is an object with a namespace, often backed by a Python source file. Importing a module gives you access to the names it defines. The standard library supplies many modules with Python, so you can use tools such as math and statistics without installing a third-party package. Start by reading the contract for the particular function you need rather than guessing what its name implies.

With import math, the name math refers to the module. math.ceil accesses its ceil function, which returns the smallest integer greater than or equal to a number. Keeping the module prefix makes a function's source visible at the call site. This is especially useful when a program uses several libraries or when common names such as mean might otherwise be ambiguous.

standard_library_tools.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

02Import styles bind different names

from math import ceil binds ceil directly in the current namespace. import statistics as stats binds the module under a shorter alias. These styles can improve readability when used consistently, but they change which names are available. After importing only ceil, do not assume the name math has also been bound. Avoid wildcard imports because they make a file's name sources harder to see.

An import normally initializes a module on its first import in a process, then reuses the cached module for subsequent imports. Do not rely on importing again to rerun initialization or refresh edited code; restart a small script while learning. Name your files carefully: a local file called math.py or statistics.py can hide the standard module you intended to import, causing confusing missing-name or circular-import errors.

explicit_imports.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.

03Write your own importable file

To organize your code, save the following source as study_tools.py in a fresh folder. Its function is available when another file imports study_tools. The body of a function does not run merely because the function is defined, but ordinary statements at the module's top level do run during initialization. An unguarded demonstration print would therefore also run when someone imports the file.

Python sets __name__ to '__main__' for the file being executed as the main program. The guard below uses that distinction to run a demonstration only when study_tools.py is executed directly. Importing it defines total_minutes without printing the demonstration. This snippet is one part of a two-file exercise. Save both source files locally and use your installed Python interpreter; the website displays code and expected output.

study_tools.pyPython
def total_minutes(sessions):    """Return the sum of nonnegative study-session durations."""    valid = [minutes for minutes in sessions if minutes >= 0]    return sum(valid)if __name__ == "__main__":    print(total_minutes([10, 20]))
Outputstdout
30

04Connect the files through a small main program

Save this second file as main.py beside study_tools.py. In a terminal opened in that folder, run python main.py using the interpreter command established in the setup lesson. That is a terminal command, not an additional line for either source file. Python can find the sibling module using the script's directory. Keep the module filename and the spelling in the import consistent.

The imported function performs a calculation while main chooses the input data and presentation. The guard makes the entry point explicit here too. When running main.py, expect only its summary line; study_tools.py's guarded demonstration should remain silent. If you see both messages, inspect the indentation and guard. This small project brings together functions, collection processing, imports, and a clear boundary around visible output.

main.pyPython
from study_tools import total_minutesdef main():    sessions = [25, -5, 30, 0]    total = total_minutes(sessions)    print(f"Total study time: {total} minutes")if __name__ == "__main__":    main()
Outputstdout
Total study time: 55 minutes
LET IT CLICK

The ideas worth keeping.

  • Imports bind names that provide access to module namespaces or selected members.
  • Use explicit import styles and avoid filenames that hide standard-library modules.
  • A main guard separates direct execution from reusable imported definitions.
TURN UNDERSTANDING INTO SOMETHING YOU CAN DO

Make it yours.

Type and test your code right here in the interactive workspace. Run your solution, check the output, and compare with the worked guide when ready.

01

Choose a standard-library tool

Use the math module to calculate how many 4-seat tables are needed for 18 people. Divide the people count by the capacity, then round upward with ceil. Keep the module name visible at the call site.

your_turn_1.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.pyPython
import mathpeople = 18seats_per_table = 4tables = math.ceil(people / seats_per_table)print(tables)

The exact quotient is 4.5, so five complete tables are needed. math.ceil communicates rounding upward; floor division alone would under-allocate seats.

02

Make a reusable entry-point file

Create a single importable file with square(number) returning number ** 2 and main() printing square(7). Use a main guard so importing the file would define the functions without printing.

your_turn_2.py🐍Python
Ctrl + ↵
Output
Click Run or press Ctrl+Enter
Output will appear here after you run the code.
Explore a worked solution
one_possible_solution.pyPython
def square(number):    return number ** 2def main():    print(square(7))if __name__ == "__main__":    main()

Direct execution prints 49. During import, __name__ is the module's name rather than __main__, so the guarded call is skipped and square remains available for reuse.

A SMALL QUESTION. A USEFUL NEXT STEP.

What stayed with you?

Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.

A LITTLE ACTIVE RECALL0 / 3 answered
01After import math, how do you call its ceil function?
02Why put a demonstration call inside if __name__ == '__main__':?
03Your script is named statistics.py and import statistics cannot find mean as expected. What is a likely cause?
⚡CODING CHALLENGE
🔒Required to Mark Lesson Complete

Choose a standard-library tool

Use the math module to calculate how many 4-seat tables are needed for 18 people. Divide the people count by the capacity, then round upward with ceil. Keep the module name visible at the call site.

EXPECTED OUTPUT
math.ceil(people / seats_per_table)
challenge.pyPython 3
Ctrl + ↵
Execution Console
Click "Run & Verify" (or press Ctrl + Enter) to test your code against the challenge.

Keep exploring.

The official references behind this chapter, when you want a second angle or the full details.

One chapter closer.

Reading is a start. Trying it yourself makes the connection.

Solve the hands-on coding challenge in the knowledge section to verify your code and unlock chapter completion.