Python | Modules | Create a Python module

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 then add to it the following code:

def subtraction(num1,num2):
	result = num1 - num2

We created a function that takes in two parameters, num1 and num2. The next line is a variable named result which has the value of num1 – num2. Finally, we return the value of the result.

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 and place the following code in it.

import mymodule
result = mymodule.subtraction(9,4)

We import the file/module into the file.

The variable result is assigned a value. It uses the function subtraction() from the module to subtract 4 from 9. The result, 5, is assigned as value to the variable result then it is printed on the screen.

Python Create a module

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.

Leave a Reply