Showing posts with label creating module in python. Show all posts
Showing posts with label creating module in python. Show all posts

Sunday, October 22, 2017

How to Create Your Own Module

The simplest way to create your own module is by using function in Python. Python provide a cest way to create your own module. For example suppose you have function like below -

def myModule(wannasay):
'''This module will say whatever you wanna say'''
return "I wanna say"+str(wannasay)
def calculate(x,y): '''This will add two numbers''' return x+y

    
Save the above code by naming it myModule.py and save it in same directory where you want to create a file which will call it.This is the way we have created the module with methods MyModule and calculate. In the program where we need the module we have to do only one thing is just to import it by the 'import' statement. Lets see how it is done -

import myModule

print "I wanna say something"
myModule.myModule("I am a bad ass lier")

print "Now I wanna calculate"
myModule.calculate(4,6) 


Up, we have imported the file. We put the module file in the same location as the file which called it. We can also put the module in the path of python, where the calling file will automatically search.  Now we used the functions in the module the same way we generally use function in python.

You can find the files here to test yourself -
https://drive.google.com/file/d/0Bx4xTppgmBd-N2wtY2ktVUItQm8/view?usp=sharing
https://drive.google.com/file/d/0Bx4xTppgmBd-SWQ3Uk9GWUZPRUU/view?usp=sharing


Feautured Post

Python Trivia Post: enumerate()

Python has a very useful inbuilt function, which is called enumerate(). This is needed whenever you need the numbering of a certain element...