Modules | Python programming

HacksLand | The computer science playground

Posted by Thilan Dissanayaka on Aug 12, 2019
Module is a simple but powerful concept in python. We saw in C programs we used header files. ( studio.h , string.h , conio.h etc) In hear we use a similar thing called module. We can call a module as a collection of functions. There are hundred of per built modules for various tasks. Also we can make our own modules. In following example I make a module called . After I import it in our main python program with Command 'import'.
[email protected]:~/programming$ cat
def calculate(a, b):
    c = (a + 2*b)-3
    return c
def printOut():
  print("hear we print a string")
[email protected]:~/programming$ cat
#!/usr/bin/env python
import myModule as module1
#now we can use's functions.
print (module1.calculate(2, 3))

[email protected]:~/programming$ python
hear we print a string

[email protected]:~/programming$ python3
hear we print a string
First we want to talk about there are no special things there. We have defined some functions in that file but we haven't call those functions. Next the syntax for importing a module is following. import module_name Or import module_name as new_name In our above example we have used second method. So we have given a name when we importing the module. Then we can refer module's functions with that name. Note that the syntax for importing modules is same in both versions of python. Let's assume that we imported our module( with first method. import myModule So now we want to access it's functions with module name like this. myModule.printOut() myModule.calculate() But I suggest you to use second method. Always give a new name when you import a module. Also there is another method for importing a module. That is importing only a required function from a module like following. from sys import argv Hear we imported argv function from the sys module. This method has a benefit when comparing with above one. This will reduce memory allocation because you only import a one function instead of importing all big module. I think now it's clear how to import a module and how to use it. There are lot of important modules like requests, urliib2, time , threading etc. I'll make separate tutorials for explain those. Till then read other tutorials and master them. Thanks for reading

Hi, I'm Thilan. An engineering student from SriLanka. I love to code with Python, JavaScript PHP and C.

Also read

Aug 12
What is a cookie?

If you are working with web applications you may have heard about cookies. Also when we browsing....

Aug 12
Inputs in C

In this tutorial I'll explain you how to get an input from the user in C language. You know that in....

May 04
C programming strings

In our "Manipulating data with C" article we saw how we can store data in memory. We used the....