Home Tutorials Python Tutorial Modules
Modules

Modules


Definition: A module is a file containing Python definitions and statements (such as functions, classes, and variables). Essentially, it is a code library that you can include in your project to reuse existing logic.

Why: As programs grow larger, keeping all your code in a single file becomes unmanageable. Modules help you organize your project into separate, logical files, making the codebase cleaner, easier to maintain, and highly reusable.

Types of Modules

  • Built-in Modules: Libraries that come pre-installed with Python (e.g., math, random, datetime, os).
  • User-defined Modules: Custom Python files (e.g., my_functions.py) that you create yourself and import into other files.
  • External Modules: Libraries created by the community that you can install using package managers like pip (e.g., requests, pandas).

Example (Using a Built-in Module)

import math

# Using a function from the imported math module
result = math.sqrt(25)
print(result)  # Output: 5.0

Explanation

  • The import Keyword: This tells Python to load the specified module (in this case, math) into your current script.
  • Dot Notation: To access a function inside a module, you use the module name followed by a dot and the function name (math.sqrt()). This specifies exactly where the function is coming from.

Alternative Ways to Import

Python offers flexible ways to bring module features into your workspace depending on your needs:

# 1. Importing specific functions directly (no need to use 'math.' prefix)
from math import sqrt
print(sqrt(16))  # Output: 4.0

# 2. Importing a module with an alias (renaming it for convenience)
import math as m
print(m.sqrt(9))  # Output: 3.0

Key Notes

  • Any Python file you save with a .py extension can technically be imported as a module into another file located in the same directory.
  • It is standard practice to place all import statements at the very top of your Python file.
  • Importing only what you need (using the from ... import ... syntax) can make your code slightly cleaner, but be careful not to accidentally overwrite functions with identical names.
Example

🏋️ Test Yourself With Exercises

Take our quiz on Modules to test your knowledge.

Exercise »