By the end of this lesson, you will be able to:
🎯 Explain the purpose of Python modules and packages.
🎯 Use built-in Python modules in your code.
🎯 Create and import custom modules
This lesson introduces you to the idea of organizing your code using modules and grouping them into packages. Python becomes even more powerful when you split your code into multiple files and reuse them using modules and packages. You’ll learn how to import, use, and even create your own modules, and how packages help in maintaining large codebases.
Python Syntax
import module_name
module_name.function_name(arguments)
Python Code
import math
print("Square root of 49:", math.sqrt(49)) # Output: 7.0
print("Value of pi:", math.pi) # Output: 3.14159...
import random
print(random.randint(1, 10)) # Random integer from 1 to 10
print(random.choice(['A', 'B', 'C'])) # Random choice from list
import datetime
now = datetime.datetime.now()
print("Current time:", now)
print("Today's date:", datetime.date.today())
Open Google Colab, create a new notebook, and run the examples above in new code cells.
Python Code
import random
def roll_die():
return random.randint(1, 6)
print("You rolled a", roll_die())
Run the examples above in new code cells.
You are helping organize a virtual Lucky Draw Contest for a college event. Participants have registered online, and their names are stored in a list. Your task is to write a Python program that randomly selects winners using the random module.
You are given a list of participant names. Your program should:
Randomly select one grand prize winner
Randomly select three consolation prize winners (without repeating the grand prize winner)
Display the results neatly
Sample Data:
participants = ["Afiq", "Zara", "Daniel", "Liyana", "Nina", "Ravi", "Sofia","Haris", "Esha", "Kavya", "Arjun", "Bella", "Nabil", "Farah"]
Step 1: Import random module
Step 2: Randomly select 1 grand price winner
Step 3: Select 3 unique consolation winners
Step 4: Final Output
Python Syntax
from module_name import function1, function2
Python Code
from math import sqrt, pi
print("Square root of 49 is", sqrt(49)) # 7.0
print("Value of pi is", pi) # 3.1415...
# No need to write math.sqrt()
from random import randint, choice
print(randint(1, 100)) # Random number between 1 and 100
print(choice(['red', 'blue'])) # Randomly selects an item
from datetime import datetime, timedelta
now = datetime.now()
print("Now:", now)
future = now + timedelta(days=5)
print("Five days later:", future)
Run the examples above in new code cells.
Python Code
from statistics import mean, median
data = [12, 15, 18, 21, 24]
print("Mean:", mean(data))
print("Median:", median(data))
Run the examples above in new code cells.
You are developing a simple fitness tracking program for beginners. One of the features is calculating the distance covered by a user while jogging or walking in a circular park.
The park has a circular track, and users record the number of laps and the radius of the track (in meters). Your program should calculate the total distance walked using the formula for the circumference of a circle:
Distance=2×π×radius×laps
To simplify and write clean code, you'll import only the pi function from Python’s built-in math module.
Create a Python program that:
Imports only the pi constant from the math module
Accepts the radius of the track and number of laps as user input
Calculates and displays the total distance walked in meters
Rounds the result to 2 decimal places
Step 1: Import only pi
Step 2: Get user input (radius and lap)
Step 3: Calculate the distance
Step 4: Display Output
Use common aliases (pd, np, plt) — they’re universally recognized.
Choose short, clear aliases if you’re making custom ones.
Don’t use confusing or unrelated aliases.
Python Syntax
import module_name as alias
Python Code
import math as m
print(m.sqrt(36)) # Output: 6.0
print(m.pi) # Output: 3.1415...
import random as rnd
lucky_number = rnd.randint(1, 100)
print("Your lucky number is:", lucky_number)
import datetime as dt
current_time = dt.datetime.now()
print("Current time:", current_time)
Run the examples above in new code cells.
You are developing a simple program called "Daily Inspiration" that displays a random motivational quote along with the date and time it was shown. The program will be part of a digital dashboard for students and staff.
To keep the code clean and professional, you decide to:
Use the random module with the alias rnd
Use the datetime module with the alias dt
quotes = [
"Believe you can and you're halfway there.",
"Success is not final, failure is not fatal.",
"Do one thing every day that scares you.",
"Hard work beats talent when talent doesn't work hard.",
"Stay hungry. Stay foolish."
]
Step 1: Import modules with aliases
Step 2: Create a list of motivational quotes
Step 3: Select a random quote and get the current time
Step 4: Display the quote with the timestamp
Full Module Import Access full module using prefix need many functions from a module import math
math.sqrt(25)
Specific Import Access only selected functions need only 1–2 functions from math import sqrt
/classes sqrt(25)
Using Alias Shorten module name the module name is long import pandas as pd
pd.DataFrame()
Python Code
def add(a, b):
return a + b
def subtract(a, b):
return a - b
Python Code
import my_math
print("Addition:", my_math.add(10, 5))
print("Subtraction:", my_math.subtract(10, 5))
NOTE: my_math.ipynb need to be in the same folder as main.ipynb
Python Code
from my_math import add
print(add(7, 3)) # Only importing and using `add`
Run the examples above in new code cells.
File name: greeting.py
Python Code
def say_hello(name):
return f"Hello, {name}!"
def say_goodbye(name):
return f"Goodbye, {name}!"
Part 2: Create a Main Program (app.ipynb)
File name: app.py
Python Code
import greeting
print(greeting.say_hello("Afiq"))
print(greeting.say_goodbye("Afiq"))
NOTE: greeting.ipynb need to be in the same folder as app.ipynb
Run the examples above in new code cells.
You’ll write a module called text_utils.py with functions like:
Counting the number of words in a string
Reversing a sentence
Making all text uppercase
Then, you'll use those functions in another script.
Step 1: Create a new file named text_utils.py
Step 2: Create another file called main.py
Sample Output:
Original: Python makes coding fun and powerful
Word count: 6
Reversed: lufrewop dna nuf gnidoc sekam nohtyP
Uppercase: PYTHON MAKES CODING FUN AND POWERFUL
🧠 Answer these to test your understanding.
What is a Python module?
a) A block of repeated code
b) A built-in function
c) A Python file containing reusable code
d) A folder of images
Which of the following correctly imports an entire module?
a) from math import sqrt
b) import sqrt from math
c) import math
d) math import
Which statement imports only the pi constant from the math module?
a) import math.pi
b) from math import pi
c) math from import pi
d) include math.pi
What is an alias in Python imports used for?
a) Hiding a module
b) Creating a backup
c) Shortening the module name
d) Encrypting data
You can only import built-in Python modules, not your own (T/F).
The same function name can be used in different modules (T/F).
import my_module will work only if my_module.py is in the same directory or Python path (T/F).
You must always use as when importing a module (T/F).
🔧 Instructions:
Task Title: Student Helper Module: Your Academic Assistant
By completing this task, you will:
Understand how to write and save your own Python module
Practice writing simple functions inside a separate .py file
Import your custom module into another Python script
Use imported functions to perform tasks and display output
You are building a student helper system that helps calculate average marks and determine grades. Your solution should be organized using two separate Python files:
PART A: A module file that contains the logic
PART B: A main program that uses (imports) the module
Part A: Create Your Module File
Open your Google Colabs
Create a new notebook and save it as: student_helper.py
Inside student_helper.py, write and save the following functions: calculate_average and get_grade.
Part B: Create Your Main Program
In the same folder, create another new file and save it as: main.py
In main.py, do the following:
Import your module using: import student_helper
Ask the user to enter three subject marks using input()
Call the calculate_average() function from the module
Call the get_grade() function using the average value
Display the average (2 decimal places) and the grade
✅ Hint: You will need to convert the user input to numbers using float().
🔹 A module is any .py file that can be imported.
🔹 You can reuse code by importing it from other modules.
🔹 Built-in modules like math and random offer ready-made tools.
🔹 You can import the whole module, specific items, or use aliases.
🔹 Organizing code into modules makes your projects scalable and maintainable.