Mini Project: Math Utilities
Build a reusable math utility module with multiple functions
Writing code and entering commands is only available on desktop. Open this page on a larger screen to complete this chapter.
Putting it all together
You now know how to import modules, create your own, and guard top-level code with __name__. Time to build something real.
In this mini project, you build a math_utils module — a collection of math functions that any project can import. The module includes functions for averages, factorials, and checking prime numbers.
Designing a module
A good utility module follows a pattern:
- Each function does one thing.
calculate_averagecomputes an average. It doesn't also print it or write it to a file. - Functions take inputs and return outputs. No global variables, no side effects. This makes functions easy to test and reuse.
- The
__name__guard demos the module. Running the file directly shows each function in action.
This is the same pattern used by Python's built-in modules. math.sqrt() takes a number and returns a number. It doesn't print, doesn't ask for input, doesn't modify anything outside itself.
Your task
Build four functions in a single file. Each function solves a small math problem. The __name__ guard at the bottom runs a demo of all four functions.
Instructions
Build the math utilities module.
- Define
calculate_average(numbers). Returnsum(numbers) / len(numbers). - Define
find_max(numbers). Create a variable namedmaximumand set it tonumbers[0]. Loop through eachnuminnumbers. Ifnumis greater thanmaximum, setmaximumtonum. Returnmaximum. - Define
factorial(n). Create a variable namedresultand set it to1. Loop throughrange(1, n + 1)with loop variablei. Multiplyresultbyi. Returnresult. - Define
is_prime(n). Ifnis less than2, returnFalse. Loop throughrange(2, int(n ** 0.5) + 1)with loop variablei. Ifn % iequals0, returnFalse. After the loop, returnTrue. - Add the
if __name__ == "__main__":guard. - Inside the guard, call
print()withcalculate_average([10, 20, 30, 40, 50]). - Inside the guard, call
print()withfind_max([3, 7, 2, 9, 1]). - Inside the guard, call
print()withfactorial(5). - Inside the guard, call
print()withis_prime(17). - Inside the guard, call
print()withis_prime(15).
# Step 1: Define calculate_average(numbers) # Step 2: Define find_max(numbers) # Step 3: Define factorial(n) # Step 4: Define is_prime(n) # Step 5: Add the __name__ guard # Step 6: Print calculate_average([10, 20, 30, 40, 50]) # Step 7: Print find_max([3, 7, 2, 9, 1]) # Step 8: Print factorial(5) # Step 9: Print is_prime(17) # Step 10: Print is_prime(15)
Interactive Code Editor
Sign in to write and run code, track your progress, and unlock all chapters.
Sign In to Start Coding