A Python module is just a python file, a file that has the extension
.py. So, in order to create your first module you have to create that file. Create a file and name it
mymodule.py then add to it the following code:
def subtraction(num1,num2): result = num1 - num2 return(result)
We created a function that takes in two parameters,
num2. The next line is a variable named
result which has the value of
num1 – num2. Finally, we return the value of the
We can use this module as we like. For that, we need to import it wherever we want to use it.
Let’s create another file and name it
sub_mymodule.py and place the following code in it.
import mymodule result = mymodule.subtraction(9,4) print(result)
We import the
mymodule.py file/module into the
result is assigned a value. It uses the function
subtraction() from the module
mymodule.py to subtract 4 from 9. The result, 5, is assigned as value to the variable
result then it is printed on the screen.
Both files created here should be in the same directory in your computer otherwise you have to specify the full path to the imported file.