CodingNic

Modules, Packages, and Virtual Environments

What Is a Module

Modules, Packages, and Virtual Environments 22 min read

What Is a Module

What Is a Module

As programs grow, one file can become too large and hard to manage.

Python uses modules to organize code.

What Is a Module?

A module is a Python file that contains code.

It can contain:

  • variables
  • functions
  • classes

Example:

text
math_tools.py

This file is a module.

Why Modules Matter

Modules help you:

  • split code into files
  • reuse code
  • keep projects organized
  • make code easier to read

Example Without Modules

Everything in one file:

python
def add(a, b):
    return a + b

print(add(2, 3))

This works, but large projects become messy.

Example Module File

Create a file named:

text
math_tools.py

Add:

python
def add(a, b):
    return a + b

Use the Module

Create another file:

text
main.py

Add:

python
import math_tools

print(math_tools.add(2, 3))

Output

text
5

Real Examples of Modules

  • math
  • random
  • os
  • json

These are built-in modules.

One Project, Many Modules

Example project:

text
main.py
users.py
products.py
reports.py

Each file handles one job.

Code Along

Create:

text
greetings.py

Add function:

python
def hello():
    print("Hello")

Import it in main.py.

Mini Challenge

Create a module named:

text
tools.py

Add function:

python
def double(number):
    return number * 2

Use it in another file.

Expected output:

text
10

Real World Use Case

Large apps use many modules for users, payments, reports, files, and settings.

Quiz

  1. What is a module?
  2. What can a module contain?
  3. Why are modules useful?
  4. Is every .py file a module?

Assignment

Create a module with one function that prints your name, then import it.

Summary

You learned that a module is a Python file used to organize and reuse code.