16
Learning Python- Intermediate course: Day 7, Making Python modules
We have learnt how to use predefined python modules. Today we will create our very own Python module. π€© So put your seatbelts on for this thrilling Python journeyπ
-
Step I Make a python file named mymodule.py (or any other name ending with
.py
) which contains various functions. Do this in Python IDLE or any other IDE. Here is a sample file-
def hi():
print("hi")
def hello():
print("hello")
def add(a,b):
return a+b
def printer(a):
print(a)
- Step II Save the python file (or copy-paste the file) in the Lib (not libs) folder of the Python source code.
-
Step III In the file in which you want to use the module, write
import mymodule
(import the relevant module name) After that, just use the functions in the module as predefined functions. Simple !!
Here is the program which uses the functions in our module.
import mymodule
mymodule.printer("Welcome to Python intermediate course!")
print(mymodule.add(2,3))
mymodule.hello()
OUTPUT-
Python 3.10.0a2 (tags/v3.10.0a2:114ee5d, Nov 3 2020, 00:37:42) [MSC v.1927 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license()" for more information.
>>>
= RESTART: C:/Users/aatma/AppData/Local/Programs/Python/Python310/Lib/mymoduletester.py
Welcome to Python intermediate course!
5
hello
That's it! We have successfully made our own module and used it in our code!π€ Cool!π
I have used the IDLE for Python over here, but you are free to use any editor you want. We can have the same effect by using the online GDB compiler as shown below.
βοΈSo friends that's all for now. π Hope you all are having fun.π Please let me know in the comment section below π. And don't forget to like the post if you did. π I am open to any suggestions or doubts. π€ Just post in the comments below or gmail me. π
Thank you allπ
Also please visit the Learning-Python repo made especially for this course and don't forget to star it too
16