Aside from importing in-built modules, we can also create our own modules. This is useful especially when you want to reuse a function in future projects.
To make a module, we save a file with our function as a .py file and put it in the same folder as the file we will import it from.
For example, if we want to use the checkIfPrime() function that we defined earlier in another project, here is how we do it:
1. We will save the code as prime.py on our desktop.
prime.py should have the code:
def checkIfPrime(numberToCheck):
for x in range(2, numberToCheck):
if (numberToCheck%x == 0):
return False
return True
2. We make another Python file and name it useCheckIfPrime.py and save it on our desktop as well. useCheckIfPrime.py should have the code:
import prime
answer = prime.checkIfPrime(13)
print(answer)
Now run useCheckIfPrime.py. The output should be True.
However, if we store prime.py and useCheckIfPrime.py in different folders, we'll have to some codes to useCheckIfPrime.py to tell the interpreter to find the module.
Let us say that we made a folder called MyPythonModules in the C drime to store prime.py. We'll need to add the following code at the very top of the useCheckIfPrime.py file.
import sys
if 'C:\\MyPythonModules' not in sys.path:
sys.path.append('C:\\MyPythonModules')
sys.path 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, we can put prime.py in C:\MyPythonModules and useCheckIfPrime.py in any folder you like.
No comments:
Post a Comment