Modules
Modules are simply ".py" files that contain python definitions and functions. Those functions can be later imported by other scripts. They have their own private symbol table so names of the functions won't clash with your main script.
This could be a file or module named "math.py"
#math.py
def add(n1, n2):
"""Adds two numbers"""
return n1 + n2
def subtract(n1, n2):
"""Subtract n2 from n1 numbers"""
return n1 - n2
def multiply(n1, n2):
"""Multiply two numbers"""
return n1 * n2
def divide(n1, n2):
"""Divide one number by the other"""
return n1 / n2
Â
This would then be how you would use it in another script called test.py
# using the functions within math.py
import math
print(math.add(1, 2))
print(math.subtract(2, 1))
print(math.multiply(2, 2))
print(math.divide(2, 1))
Â
This new file which calls functions from the imported module is also a module. To call it from the command line just run:
python test.py