Introduction

Size of software or application can grow and getting complex from time to time.

If you want to write a scaleable, readable and manageable application you need to organize in proper ways. This is where modular programming as a software design technique come into place by split huge pile of codes into small chunk and separate parts.

Pre-requisited:

  • Basic knowledge about Python
  • Python3.xx version installed
  • Terminal or Python interpreter that run Python script
  • Run your code as superuser. If a line start with ‘$’ means run the file in terminal as superuser.

Why you need to have a module?

The main purpose is to make code reusable.

A module are collection of classes, functions and variables that shares within an application to minimize error and remove duplication or redundancy with adhere a principle of DRY Dont-Repeat-Yourself

In Python, a module is a self-contained file with Python statements, definition and expression. Let say a file name calculator.py is considered as a module named calculator.

Our tutorial for module will consist of:

  • Introduction
    • A simple function
    • Enhance function
  • Create a module
    • Applying a module
  • Python import module
  • Create and import a module
  • Import Class, function and variable
  • Bundle multiple modules inside package

A simple function

For purpose of this tutorial I would like to create a single file named main.py
that count two inputs and sum it together.

# main.py
# sum between two integer/float inputs

a = int(input("What is your first integer input: "))
b = int(input("What is your second integer input: "))

def add(a, b):
    """
    This program add between two inputs and return the result.
    """
    result = a + b
    return result

total = add(a, b)
print("Total is: ", total)

Let explain this by line from top to bottom:

  • Prompt users for input for a as first input and b as second input
  • Define a function name add to add two inputs a and b
  • Assign add function to total
  • Print total

Then you run file main.py this in your terminal as:

$ python3 main.py

Next put two inputs as shown below:

What is your first integer input: 2
What is your second integer input: 3
Total is:  5

Ok, for now we have seen quite simple feature that add two inputs integer and print the total.

Enhanced function

Now, let say we want to add more features. Instead of add between two input integers we want to have more operators like subtract, multiply and division.

Here we go. Let copy our previous file
main.py and save as main1.py while alter exising code and more into the script.

# main1.py
# sum between two integer/float inputs

# Section-1: Prompt users for input

num_1 = int(input("What is your first integer input: "))
num_2 = int(input("What is your second integer input: "))

operator = (input("Select your operator either +,-,*,/: "))

# Section-2: Create more functions- add, minus, multiply, divide

def add(a, b):
    """
    This program ADD between two inputs and return the result.
    """
    result = a + b
    return result

def minus(a, b):
    """
    This program MINUS between to integer inputs and return the result.
    """
    result = a - b
    return result

def multiply(a, b):
    """
    This program MULTIPLY between to integer inputs and return the result.
    """
    result = a * b
    return result

def divide(a, b):
    """
    This program DIVIDE between to integer inputs and return the result.
    """
    result = a / b
    return result

# Section-3: Create a function that put conditional statement base on operator while pulling above functions

def calculate(num_1, num_2):
    """
    This will invoke either one from above functions:
    - add
    - minus
    - multipy
    - divide
    """

    if operator == '+':
        total = add(num_1, num_2)
        return total

    elif operator == '-':
        total = minus(num_1, num_2)
        return total

    elif operator == '*':
        total = multiply(num_1, num_2)
        return total

    else:
        total = divide(num_1, num_2)
        return total

## Section-4: Print out the result as required

answer = calculate(num_1, num_2)
print('{} {} {} = {}'.format(num_1, operator, num_2, answer))

Here we create an enhanced features that can calculate using either four different operators between 2 inputs integer. Above script file name main1.py has 4 sections. We go by sections to know what it does:

  • Section 1: Ask for user inputs that ask for two inputs integer and choose an operator either +, -, *, /.
  • Section 2: Create function as each solve for ADD, MINUS, MULTIPLY & DIVIDE.
  • Section 3: A calculate function created that comprise all operator function in conditional statements that return a value.
  • Section 4: This produce the output desire and assign to print statement under .format function for each of variable store in user inputs.

Run file main1.py this in your terminal as:

$ python3 main1.py

Here is what can you expect and this is what it looks like when I put 235 and 5 follow by / as division operator.

What is your first integer input: 235
What is your second integer input: 5
Select your operator either +,-,*,/: /
235 / 5 = 47.0

Let pause a bit. Look what we had achieved. Think about it as we add more features it add extra lines of code. What if we want to additional feature to our main1.py such as alert or trigger input error like put a string instead of integer or we want to loop our function until we decide to quit.

Definitely the size getting bigger and as well complexities.

Create a module

Applying a module

It is time to create a module to split and separate into different file.

Now copy your main1.py file and save as main2.py. Then you create a new file of module name as calculator.py.

Remember that main2.py has 4 different sections. Cut code in Section-2 and Section-3 and paste it into empty file that had created just now name calculator.py.

File main2.py.

# main2.py
# sum between two integer/float inputs

# Section-1: Prompt users for input

num_1 = int(input("What is your first integer input: "))
num_2 = int(input("What is your second integer input: "))

operator = (input("Select your operator either +,-,*,/: "))

# Section-4: Print out the result as required

answer = calculate(num_1, num_2)
print('{} {} {} = {}'.format(num_1, operator, num_2, answer))

File calculator.py.

# calculator.py
# sum between two integer/float inputs

# Section-2: Create more functions- add, minus, multiply, divide

def add(a, b):
    """
    This program ADD between two inputs and return the result.
    """
    result = a + b
    return result

def minus(a, b):
    """
    This program MINUS between to integer inputs and return the result.
    """
    result = a - b
    return result

def multiply(a, b):
    """
    This program MULTIPLY between to integer inputs and return the result.
    """
    result = a * b
    return result

def divide(a, b):
    """
    This program DIVIDE between to integer inputs and return the result.
    """
    result = a / b
    return result

# Section-3: Create a function that put conditional statement base on operator while pulling above functions

def calculate(num_1, num_2):
    """
    This will invoke either one from above functions:
    - add
    - minus
    - multipy
    - divide
    """

    if operator == '+':
        total = add(num_1, num_2)
        return total

    elif operator == '-':
        total = minus(num_1, num_2)
        return total

    elif operator == '*':
        total = multiply(num_1, num_2)
        return total

    else:
        total = divide(num_1, num_2)
        return total

Next, you need to call your function from module file name calculator.py into main2.py. Make sure you copy this or type a line at the top right before Section-1.

import calculator       # import module file name calculator.py

Even though we had our line statement to import calculator module but still we haven’t yet specify it in our code in Section-4 at 2nd last line using dot notation function.

answer = calculator.calculate(num_1, num_2)     # add calculator using dot notation

Here is your altered version of main2.py:

# main2.py
# sum between two integer/float inputs

import calculator       # import module file name calculator.py

# Section-1: Prompt users for input

num_1 = int(input("What is your first integer input: "))
num_2 = int(input("What is your second integer input: "))

operator = (input("Select your operator either +,-,*,/: "))

# Section-4: Print out the result as required

answer = calculator.calculate(num_1, num_2)     # add calculator using dot notation
print('{} {} {} = {}'.format(num_1, operator, num_2, answer))

Let see if it works. Run file main2.py in your terminal as:

$ python3 main2.py

Now, you can see that it throws an error in your terminal as below:

What is your first integer input: 21
What is your second integer input: 12
Select your operator either +,-,*,/: +
Traceback (most recent call last):
  File "main2.py", line 15, in <module>
    answer = calculator.calculate(num_1, num_2)
  File "/home/python-tutorial/modular-programming-with-modules/calculator.py", line 45, in calculate
    if operator == '+':
NameError: name 'operator' is not defined

What went wrong? Take a look at Traceback notice:

  • In file main2.py is trying to locate operator assignment as requires by user input from module name calculator but Python cannot find it.
  • The reason it fails because in Python we cannot access variable inside function from separate files like module.
  • What we need to do is to create a paramater name operator in both file main.py and calculator.py.

Let fix main2.py:

# main2.py
# some code here ..

# Section-4: Print out the result as required

# add operator as parameter
answer = calculator.calculate(num_1, num_2, operator)     # add calculator using dot notation

Next, add parameter in our module file name as calculator.py. You can add the same parameter operator into module calculator.

# calculator.py
# some code here ....

# section-3: create a function that put conditional statement base on operator while pulling above functions

def calculate(num_1, num_2, operator):    # add 'operator' parameter

This will be the update version of both files main2.py and calculator.py.

# main2.py
# sum between two integer/float inputs

import calculator

# Section 1: Prompt users for input

num_1 = int(input("What is your first integer input: "))
num_2 = int(input("What is your second integer input: "))

operator = (input("Select your operator either +,-,*,/: "))

# Section 4: Print out the result as required

# add operator as parameter
answer = calculator.calculate(num_1, num_2, operator)     # add calculator using dot notation
print('{} {} {} = {}'.format(num_1, operator, num_2, answer))

Latest update calculator module.

# calculator.py
# sum between two integer/float inputs

# Section 2: Create more functions- add, minus, multiply, divide

def add(a, b):
    """
    This program ADD between two inputs and return the result.
    """
    result = a + b
    return result

def minus(a, b):
    """
    This program MINUS between to integer inputs and return the result.
    """
    result = a - b
    return result

def multiply(a, b):
    """
    This program MULTIPLY between to integer inputs and return the result.
    """
    result = a * b
    return result

def divide(a, b):
    """
    This program DIVIDE between to integer inputs and return the result.
    """
    result = a / b
    return result

# Section 3: Create a function that put conditional statement base on operator while pulling above functions

def calculate(num_1, num_2, operator):    # add 'operator' parameter
    """
    This will invoke either one from above functions:
    - add
    - minus
    - multipy
    - divide
    """

    if operator == '+':
        total = add(num_1, num_2)
        return total

    elif operator == '-':
        total = minus(num_1, num_2)
        return total

    elif operator == '*':
        total = multiply(num_1, num_2)
        return total

    else:
        total = divide(num_1, num_2)
        return total

Run file main2.py in your terminal as:

$ python3 main2.py

Here is the output run from terminal.

What is your first integer input: 23
What is your second integer input: 12
Select your operator either +,-,*,/: +
23 + 12 = 35