Modules and Packages
Import useful code from modules, understand packages, and recognize a script's main entry point.
Reuse code from a module
A module is a Python file that contains code you can import. Python's standard library includes many ready-to-use modules, including math and random.
Use import to bring in a module, then use its name and a dot to access its tools.
import math print(math.sqrt(81)) print(math.ceil(2.1))
math.sqrt and math.ceil are names inside the math module. Keeping the module name makes it clear where the function came from.
from math import ceil as round_up print(round_up(4.2))
Use random predictably in examples
import random random.seed(0) print(random.randint(1, 10)) print(random.choice(["red", "blue", "green"]))
from ... import ... imports one name directly. as gives an imported name an alias. The random.seed(0) call makes this example repeatable; real programs often leave randomness unseeded.
Scripts, packages, and pip
def main():
print("Starting the program")
if __name__ == "__main__":
main()
When Python runs a file directly, its __name__ is "__main__", so the guarded code runs. When another file imports it, that guarded code does not run automatically.
A package is a way to organize related modules in a directory. pip is Python's package installer; it can install packages made by other people when your project needs them.
Key points
- A module is a Python file with reusable code.
- import module keeps module names visible.
- from ... import ... can import one name and as can rename it.
- Seed random in repeatable examples.
- Packages organize modules, and pip installs external packages.
Worked example
Splitting a bill fairly per head needs ceiling maths — import it from the standard library instead of reinventing it.
import math total = 1000 people = 3 per_head = math.ceil(total / people) print(per_head)
How it works, step by step
- import math brings the module into scope under its name.
- 1000 / 3 is 333.33…; ceil rounds UP so the host is not short-changed.
- Standard library = batteries included, tested by thousands.
References & Further Reading
Related entries from PyLabs's own reference library.
Practice exercise
Not passed yetImport the math module. Use math.floor to round 6.9 down, then print the result.
Expected output: 6
# Write your code below
Check yourself
Modules and Packages quiz
10 questions. You get instant feedback per question, and the timer starts when you press the button.
Lesson incomplete
Not completedCreate an ID or sign in to save lesson completion across devices.