Using Modules and Creating Your Own

50 min read Functions

This is a free course. Log in to run the code exercises and track your progress.

Using Modules and Creating Your Own

Every .py file is a module. Put related functions in one file and any other program in the same folder can import them. A folder of modules (a package) makes a library.

# numtools.py: your own module
def is_prime(n):
    if n < 2:
        return False
    for d in range(2, int(n ** 0.5) + 1):
        if n % d == 0:
            return False
    return True

def digit_sum(n):
    return sum(int(d) for d in str(abs(n)))

if __name__ == "__main__":
    print(is_prime(17))     # runs only when numtools.py itself is run

Three ways to use it from another file:

import numtools
print(numtools.is_prime(11))

from numtools import digit_sum
print(digit_sum(2025))      # 9

import numtools as nt
print(nt.is_prime(21))      # False

When a module is imported, its __name__ is the module's name; when the file is run directly, __name__ is "__main__". The if __name__ == "__main__": test therefore keeps a module's own test code from running on import. In the code runner below, everything is in one file: the functions play the part of the module.

Python exercise

The "library" part defines is_prime(n). Finish next_prime(n) so it returns the smallest prime greater than n, using is_prime. The program prints the next prime after each number on the input line.

# --- library ---
def is_prime(n):
    if n < 2:
        return False
    for d in range(2, int(n ** 0.5) + 1):
        if n % d == 0:
            return False
    return True


def next_prime(n):
    return n + 1  # keep going until is_prime says yes


# --- program ---
print(*(next_prime(int(x)) for x in input().split()))

Log in to edit and run this code.