Python Modules · Exercises
Core Python

Python Modules Exercises

4 exercises that build on the Python Modules and Imports lesson, from easy to hard. Each one is checked in your browser when you press Check. Stuck? Use the hint before peeking at the solution.

What this lesson covers: A module is a file of Python code (functions, classes and values) that you load into your program with import, so you can reuse it instead of writing it again. By the end you can import a module in three ways (import, from … import, as), use math, random, datetime and collections, split your own code into a module, and explain what if name == "main" does. You will practise: How many boxes?; Predict the imports; Fix the countdown; Most common word.

0 / 4 completed

Python Modules practice exercises

1. How many boxes?

Write code Easy

Complete the function boxes_needed(items, per_box) so it returns how many boxes are needed to pack items things when each box holds per_box. A part-full box still counts, so round up with the math module. For example boxes_needed(10, 4) is 3.

Your code
import math

def boxes_needed(items, per_box):
    # return the number of boxes (round up!)
    pass

print(boxes_needed(10, 4))

2. Predict the imports

Predict the output Medium

Read the code and type exactly what it will print. Then press Check to run it and compare.

Read this code
import math as m
from collections import Counter

print(m.floor(7.9), m.ceil(7.1))
print(Counter("banana")["a"])
print(__name__)

3. Fix the countdown

Fix the bug Medium

This code should work out how many days are left until a product launch and print Days to launch: 15, but it crashes with TypeError: 'module' object is not callable. Fix the import so days_left is calculated correctly. Keep the variable names.

Your code
import datetime

launch = datetime(2025, 3, 1)
today = datetime(2025, 2, 14)
days_left = (launch - today).days
print("Days to launch:", days_left)

4. Most common word

Write code Hard

Write a function most_common_word(text) that returns the word that appears most often in text. Treat upper and lower case as the same and return the word in lowercase. If there is a tie, return the word that appears first. Use Counter from the collections module.

Your code
from collections import Counter

def most_common_word(text):
    # 1. make the text lowercase and split it into words
    # 2. count the words with Counter
    # 3. return the most common one
    pass

print(most_common_word("the cat and the hat"))

Next lessonPython math and statistics

More Python Modules and Imports examples · All Python exercises