Mini Project: Math Utilities
Exit

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:

  1. Each function does one thing. calculate_average computes an average. It doesn't also print it or write it to a file.
  2. Functions take inputs and return outputs. No global variables, no side effects. This makes functions easy to test and reuse.
  3. 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.

  1. Define calculate_average(numbers). Return sum(numbers) / len(numbers).
  2. Define find_max(numbers). Create a variable named maximum and set it to numbers[0]. Loop through each num in numbers. If num is greater than maximum, set maximum to num. Return maximum.
  3. Define factorial(n). Create a variable named result and set it to 1. Loop through range(1, n + 1) with loop variable i. Multiply result by i. Return result.
  4. Define is_prime(n). If n is less than 2, return False. Loop through range(2, int(n ** 0.5) + 1) with loop variable i. If n % i equals 0, return False. After the loop, return True.
  5. Add the if __name__ == "__main__": guard.
  6. Inside the guard, call print() with calculate_average([10, 20, 30, 40, 50]).
  7. Inside the guard, call print() with find_max([3, 7, 2, 9, 1]).
  8. Inside the guard, call print() with factorial(5).
  9. Inside the guard, call print() with is_prime(17).
  10. Inside the guard, call print() with is_prime(15).