Python
programming
Creating our Own Module
Besides importing built-in modules, we can also
create our own modules.
This is very useful if you have some functions that
you want to reuse in
other programming projects in future.
Creating a module is simple. Simply save the file
with a .py extension and
put it in the same folder as the Python file that you
are going to import it
from.
Suppose you want to use the checkIfPrime()
function defined earlier
in another Python script. Here’s how you do it. First
save the code above
as [Link] on your desktop. [Link] should have
the following
code.
def checkIfPrime (numberToCheck):
for x in range(2, numberToCheck):
if (numberToCheck%x == 0):
return False
return True
Next, create another Python file and name it
[Link].
Save it on your desktop as well. [Link]
should have the
following code.
import prime
answer = [Link](13)
print (answer)
Now run [Link]. You should get the
output True.
Simple as that.
However, suppose you want to store [Link] and
[Link] in different folders. You are
going to have to add
some codes to [Link] to tell the Python
interpreter
where to find the module.
Say you created a folder named ‘MyPythonModules’
in your C drive to
store [Link]. You need to add the following code
to the top of your
[Link] file (before the line import
prime).
import sys
if 'C:\\MyPythonModules' not in [Link]:
[Link]('C:\\MyPythonModules')
[Link] refers to your Python’s system path. This is
the list of
directories that Python goes through to search for
modules and files. The
code above appends the folder
‘C:\MyPythonModules’ to your system
path.
Now you can put [Link] in C:\MyPythonModules
and
[Link] in any other folder of your choice.