Module 4 of 5 · Python Fundamentals Part 2 · Beginner

Modules and Packages

Duration: 5 min

What are Modules?

A module is a file containing Python code. Modules allow you to organize code into reusable pieces. Python has a large standard library of built-in modules, and you can also create your own modules.

Importing Modules

# Import entire module
import math
print(math.pi)
print(math.sqrt(16))

# Import specific items
from math import pi, sqrt
print(pi)
print(sqrt(25))

# Import with alias
import math as m
print(m.ceil(3.2))

# Import all items (not recommended)
from math import *
print(floor(3.9))

Try it in Google Colab: Open in Colab

3.141592653589793
4.0
3.141592653589793
5.0
4
3

Common Built-in Modules

# datetime module
import datetime
today = datetime.date.today()
print(f"Today: {today}")

# random module
import random
print(random.randint(1, 10))
print(random.choice(["Apple", "Banana", "Orange"]))

# os module
import os
print(os.getcwd())  # Current working directory

# json module
import json
data = {"name": "Alice", "age": 25}
json_string = json.dumps(data)
print(json_string)
Today: 2026-05-18
7
Banana
/Users/developer/Source/JapamalaApp/tf-ailearningclub-com
{"name": "Alice", "age": 25}

Creating Your Own Module

# my_module.py
def greet(name):
    return f"Hello, {name}!"

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

PI = 3.14159
No output - this is a module definition
# Using the module
import my_module

print(my_module.greet("Alice"))
print(my_module.add(5, 3))
print(my_module.PI)
Hello, Alice!
8
3.14159

Packages

A package is a directory that contains Python modules and a special init.py file. Packages allow you to organize related modules into a directory hierarchy.

💡 Tip: Use 'from module import item' when you only need specific items. Use 'import module' when you need multiple items from a module.

Learn more: https://docs.python.org/3/tutorial/modules.html

❓ What is the difference between 'import math' and 'from math import sqrt'?

← Previous Continue interactively → Next →

Related Courses