Skip to main content

Modules in Python




What are Modules in Python? 

Modules are simply a ‘program logic’ or a ‘python script’ that can be used for variety of applications or functions. We can declare functions, classes etc in a module.

A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference.

Simply, a module is a file consisting of Python code. A module can define functions, classes and variables. A module can also include runnable code.




How To Create Modules In Python?

Creating a module in python is similar to writing a simple python script using the .py extension. For the above example lets try to make a module for the various operations.

1
2
3
4
5
6
7
8
9
10
11
def add(x,y):
     return x + y
 
def sub(x, y):
     return x - y
 
def prod(x, y):
    return x * y
 
def div(x, y):
    return x / y

Save the above code in a file Calc.py. This is how we create a module in python. We have created different functions in this module. We can use these modules in our main file, lets take a look at how we are going to use them in a program.

How To Use Python Modules?

We will use the import keyword to incorporate the module into our program, from keyword is used to get only a few or specific methods or functions from a module. Lets see what are different methods to use a module in your program.

Lets say we have our file with a name main.py.

1
2
3
4
5
6
import calc as a
a = 10
b = 20
 
addition = a.add(a,b)
print(addition)

In the above code, we have created an alias using the as keyword. The output of the above code will be the addition of the two numbers a and b using the logic specified in the add function in the calc.py module.

Lets take a look at another approach.

1
2
3
4
5
from calc import *
a = 20
b = 30
 
print(add(a,b))

In the above code, we have imported all the functions using the asterisk and we can simply mention the function name to get the results. 

Python Module Path

When we import a module, the interpreter looks for the module in the build-in modules directories in sys.path and if not found, it will look for the module in the following order:

  1. Current directory
  2. PYTHONPATH
  3. Default directory
1
2
3
import sys
 
print(sys.path)

To add Your file path to the system path.You can use


m_directory="home/python_files"
sys.path.append(m_directory)
#

When you run the above code, you will get the list of directories. You can make changes in the list to create your own path. 

Comments

Popular posts from this blog

Exception Handling in Python

  Introduction   An error is an abnormal condition that results in unexpected behavior of a program. Common kinds of errors are syntax errors and logical errors. Syntax errors arise due to poor understanding of the language. Logical errors arise due to poor understanding of the problem and its solution.   Anomalies that occur at runtime are known as exceptions. Exceptions are of two types: synchronous exceptions and asynchronous exceptions. Synchronous exceptions are caused due to mistakes in the logic of the program and can be controlled. Asynchronous exceptions are caused due to hardware failure or operating system level failures and cannot be controlled.   Examples of synchronous exceptions are: divide by zero, array index out of bounds, etc.) . Examples of asynchronous exceptions are: out of memory error, memory overflow, memory underflow, disk failure, etc. Overview of errors and exceptions in Python is as follows:     Handling Exceptions   Flowch...

JENKINS BASICS

  Jenkins  – an open source automation server which enables developers around the world to reliably build, test, and deploy their software. Dashboard: " Dashboard " is the default view shown when you open Jenkins and shows an overview of all  projects configured on a  Jenkins  instance. Creating a New Project: Step 2:  In the next screen, enter the Item name, Choose the ‘Freestyle project option’ Step 3  − The following screen will come up in which you can specify the details of the job. Note  − If you repository if hosted on Github, you can also enter the url of that repository here. In addition to this, you would need to click on the Add button for the credentials to add a user name and password to the github repository so that the code can be picked up from the remote repository. Step 4 − Now go to the Build section and click on Add build step → Execute Windows batch command Before Executing and building a file. Let me describe the task which w...

NumPY In python

 NumPy Stands for numerical python How do I install NumPy? To install Python NumPy, go to your command prompt and type “pip install numpy”.  Once the installation is completed, go to your IDE (For example: PyCharm) and simply import it by typing:  “import numpy as np” Here, I have different elements that are stored in their respective memory locations. It is said to be two dimensional because it has rows as well as columns. In the above image, we have 3 columns and 4 rows available. How do I start NumPy? Single-dimensional Numpy Array: 1 2 3 import numpy as np a = np.array([ 1 , 2 , 3 ]) print (a) Output – [1 2 3] Multi-dimensional Array: 1 2 a = np.array([( 1 , 2 , 3 ),( 4 , 5 , 6 )]) print (a) O/P – [[ 1 2 3] [4 5 6]] Python NumPy Array v/s List Why NumPy is used in Python? We use python NumPy array instead of a list because of the below three reasons: Less Memory Fast Convenient The very first reason to choose python NumPy array is that it occupies less memory as co...