Modules and imports
Use the standard library and organize your own functions into files that can be imported safely.
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.
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.
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.
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]))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.
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()Total study time: 55 minutes
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.
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.
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.
Explore a worked solution
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.
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.
Explore a worked solution
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.
What stayed with you?
Check the ideas while they’re fresh. Your answers stay in this page and feedback appears as you go.
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.
math.ceil(people / seats_per_table)
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.