Hey fellas! In this article we’re gonna discuss about How to Create A Module In Python. Python is a powerful as well as friendly programming language. It is used to develop desktop apps, web, as well as pretty awesome softwares. Python is also a powerful tool for data science. So, before going further into the topic lets know What is a Python Module?
A Python module is simply a python file consisting of python codes that may include classes, functions, variables,etc. It’s a code written in python which we can reuse for our convenience. With this simple definition lets move on to our main topic.
How to Create A Module In Python?
Creating a module in Python is as simple as creating a python program. The only two steps you have to follow are:
Step 1: Write a bunch of codes for module.
First of all create a python file. You can use your favorite text editor and start. Write the functions you want to have in your code and save it as a Python executable file (.py file).
The codes I have written for examples are listed below:
def add(a,b):
return(a+b)
def subt(a,b):
return(a-b)
def mult(a,b):
return(a*b)
def divide(a,b):
return(a/b)
After I wrote these codes I saved it as newmath.py because I’m doing math here and it’s easy to remember. You can name a module as you like like tonystark.py, venom.py but be sure to make it easy to remember so that you can use it as per necessity.
Also read our article on How to make money with Whatsapp. Interesting, isn’t it?
Step 2: Use it in your code
Next step is also very easy. You have to import the module you have created by using
import module_name
import newmath (in our case)
The thing left to do is using it. You can access the functions in your module by using
module_name.function(arguments)
newmath.add(1,2) In our case.
The picture below will help you understand it more clearly. If you have any queries about the post or about Python feel free to comment or email us. Thanks for reading.