[go: up one dir, main page]

0% found this document useful (0 votes)
15 views17 pages

Modules

Modules allow Python code to be organized into reusable libraries. A module is a Python file with a .py extension that contains functions and other code that can be imported into other programs. Common built-in Python modules include math, statistics, and others that provide useful functions like trigonometric functions, statistical calculations, and more. Modules allow code to be reused, simplify programs by splitting them into focused parts, and avoid naming collisions.

Uploaded by

V MERIN SHOBI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views17 pages

Modules

Modules allow Python code to be organized into reusable libraries. A module is a Python file with a .py extension that contains functions and other code that can be imported into other programs. Common built-in Python modules include math, statistics, and others that provide useful functions like trigonometric functions, statistical calculations, and more. Modules allow code to be reused, simplify programs by splitting them into focused parts, and avoid naming collisions.

Uploaded by

V MERIN SHOBI
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 17

In Python, Modules are simply files with the “.

py” extension containing


Python code that can be imported inside another Python Program.
In simple terms, we can consider a module to be the same as a code
library or a file that contains a set of functions that you want to include
in your application.

Ready to start your data science journey?


Master 23+ tools & learn 50+ real-world projects to transform your
career in Data Science.
Enroll Now

With the help of modules, we can organize related functions, classes,


or any code block in the same file. So, It is considered a best practice
while writing bigger codes for production-level projects in Data
Science is to split the large Python code blocks
into modules containing up to 300–400 lines of code.

The module contains the following components:

 Definitions and implementation of classes,


 Variables, and
 Functions that can be used inside another program.
Let’s try to gain more understanding of the concept with the help
of an example:

Suppose we want to make an application for a calculator. We want to


include few operations in our application such as addition, subtraction,
multiplication, division, etc.

Now, here what we will be doing is to break the complete code into
separate parts and simply create one module for all these operations
or separate modules for each of the operations. And then we can call
these modules in our main program logic.

Here the core idea is to minimize the code, and if we create modules,
it doesn’t mean we can only use it for this program, but we can even
call these modules for other programs as well.

Image Source: Link

Now that we have understood the concept of modules, let us try to


understand how we can create and use a module in python and also
see some other functionalities related to Modules.

How to create Python Modules?


To create a module, we have to save the code that we wish in a file
with the file extension “.py”. Then, the name of the Python file
becomes the name of the module.

For Example,

In this program, a function is created with the name “welcome” and


save this file with the name mymodule.py i.e. name of the file, and
with the extension “.py”.

We saved the following code in a file named mymodule.py


def welcome(name):
print("Hello, " + name +" to Analytics Vidhya")

How to use Python Modules?

To incorporate the module into our program, we will use the import
keyword, and to get only a few or specific methods or functions from
a module, we use the from keyword.

NOTE: When we are using a function from a module, then we use the
following syntax:
module_name.function_name

Now to use the module which we have just created, we are using the
import statement:
For Example,

In this example, we will Import the module named mymodule, and


then call the welcome function with a given argument:
import mymodule
mymodule.welcome("Chirag Goyal")

Output:
Hello, Chirag Goyal to Analytics Vidhya

Variables in Python Modules

The module can contain functions, as already described, but can also
contain variables of all types such as arrays, dictionaries, objects, etc.

For Example,

Save this code in the file mymodule.py


person1 = {
"name": "Chirag Goyal",
"age": 19,
"country": "India"
"education”: “IIT Jodhpur"
}

For Example,

In this example, we will Import the module named mymodule, and


then try to access the person1 dictionary components:
import mymodule
a = mymodule.person1["age"]
b = mymodule.person1["education"]
c = mymodule.person1["country"]
print(a)

Output:
19

How to rename a Python Module?

We can name the file of the module whatever you like, but we have to
note that it must have the file extension “.py”.

To rename the module name, we can create an alias when you import
a module, with the help of the as keyword:

For Example,

Create an alias for mymodule with the name new_module:


import mymodule as new_module
a = new_module.person1["age"]
b = new_module.person1["education"]
c = new_module.person1["country"]
print(a)

Output:
19

How does Import from Modules work?


If we want to choose to import only some parts from a module, then
we can do this with the help of the from keyword.

For Example,

Now, we have a module named mymodule that has one function and
one dictionary:
def welcome(name):
print("Hello, " + name +" to Analytics Vidhya")
person1 = {
"name": "Chirag Goyal",
"age": 19,
"country": "India"
"education”: “IIT Jodhpur"
}

Now, Let’s try to Import only the person1 dictionary from the module
named mymodule:
from mymodule import person1
print (person1["age"])

Output:
19

NOTE: Here we have to note that when we try to import using


the from keyword, then do not use the module name when referring
to elements in the module.

For Example,

Use person1[“age”], not mymodule.person1[“age”]


Advantages of Modules

Some of the advantages while working with modules in Python is as


follows:

Reusability

Working with modules makes the code reusable.

Simplicity

The module focuses on a small proportion of the problem, rather than


focusing on the entire problem.

Scoping

A separate namespace is defined by a module that helps to avoid


collisions between identifiers.

Python Built-in Modules

As we know that the Python interactive shell has a number of built-in


functions. As a shell start, these functions are loaded automatically
and are always available, such as,

 print() and input() for I/O,


 Number conversion functions such as int(), float(), complex(),
 Data type conversions such as list(), tuple(), set(), etc.

In addition to these many built-in functions, there are also a large


number of pre-defined functions available as a part of libraries
bundled with Python distributions. These functions are defined in
modules which are known as built-in modules.

These built-in modules are written in C language and integrated with


the Python shell.

To display a list of all of the available modules in Python Programming


Language, we can use the following command in the Python console:
help('modules')

The output to the above code is shown below:

Now, let’s discuss some of the useful and frequently used built-in
modules of Python.

 Math Module
 Statistics Module

Working with Math Module of Python

Some of the most popular mathematical functions that are defined in


the math module include,
 Trigonometric functions,
 Representation functions,
 Logarithmic functions,
 Angle conversion functions, etc.

In addition, two mathematical constants- pi and e are also defined in


this module.

In Mathematics, Pi is a well-known mathematical constant. Its value


is 3.141592653589793.
>>> import math
>>> math.pi
3.141592653589793

Another well-known mathematical constant is e, which is known


as Euler’s number. Its value equals 2.718281828459045.
>>> import math
>>> math.e
2.718281828459045

Trigonometric Ratios

For calculating various trigonometric ratios for a given angle, the math
module contains several functions. The trigonometric functions such
as sin, cos, tan, etc. take the angle argument in radians. While we
are used to expressing the angle in degrees. In the math module, we
have two angle conversion functions that help us to convert the angle
from degrees to radians and vice versa:

 degrees()
 radians()

For Example,

In this example, we will be converting the angle of 30 degrees to


radians and then back again to the degree.

NOTE: π radians is equivalent to 180 degrees.


>>> import math
>>> math.radians(30)
0.5235987755982988
>>> math.degrees(math.pi/6)
29.999999999999996

For Example,

In this example, we will find the value of sin, cos, and tan ratios for the
angle of 30 degrees which in radians is equal to 0.5235987755982988
radians.
>>> import math
>>> math.sin(0.5235987755982988)
0.49999999999999994
>>> math.cos(0.5235987755982988)
0.8660254037844387
>>> math.tan(0.5235987755982988)
0.5773502691896257
You may also try some more functions of the math module such as
math.log(), math.log10(), math.pow(). math.sqrt(), math.exp(),
math.ceil(), math.floor(), etc.

To learn more about the math module, refer to the link.

Working with Statistics Module of Python

The statistics module provides functions to mathematical statistics of


numeric data. Some of the popular statistical functions are defined in
this module are as follows:

 Mean
 Median
 Mode
 Standard Deviation

Mean

The mean() method returns the arithmetic mean of the numbers


present in a list.

For Example,
>>> import statistics
>>> statistics.mean([2,5,6,9])
5.5
Median
The median() method returns the middle value of numeric data
present in a list.

For Example,
>>> import statistics
>>> statistics.median([1,2,3,7,8,9])
5.0
>>> statistics.median([1,2,3,8,9])
3.0
Mode

The mode() method returns the most common data point present in
the list.

For Example,
>>> import statistics
>>> statistics.mode([2,5,3,2,8,3,9,4,2,5,6])
2
Standard Deviation

The stdev() method returns the standard deviation on a given sample


in the form of a list.

For Example,
>>> import statistics
>>> statistics.stdev([1,1.5,2,2.5,3,3.5,4,4.5,5])
1.3693063937629153

To learn more about the statistics module, refer to the link.


NOTE: There are also other modules in Python but here we discuss
only two modules to understand how the concept of modules in
Python works and you can similarly use the other Python built-in
modules also.

What is a Python Package?


Python modules may contain several classes, functions, variables, etc.
whereas Python packages contain several modules. In simpler terms,
Package in Python is a folder that contains various modules as files.

Creating Package

Let’s create a package in Python named mypckg that will contain two
modules mod1 and mod2. To create this module follow the below
steps:
 Create a folder named mypckg.
 Inside this folder create an empty Python file i.e. __init__.py
 Then create two modules mod1 and mod2 in this folder.
Mod1.py
 Python3

def gfg():

print("Welcome to GFG")

Mod2.py
 Python3

def sum(a, b):


return a+b

The Hierarchy of our Python package looks like this:


Understanding __init__.py

__init__.py helps the Python interpreter recognize the folder as a


package. It also specifies the resources to be imported from the
modules. If the __init__.py is empty this means that all the functions of
the modules will be imported. We can also specify the functions from
each module to be made available.
For example, we can also create the __init__.py file for the above
module as:
__init__.py
 Python3

from .mod1 import gfg

from .mod2 import sum

This __init__.py will only allow the gfg and sum functions from the
mod1 and mod2 modules to be imported.

Import Modules from a Package

We can import these Python modules using the from…import


statement and the dot(.) operator.
Syntax:
import package_name.module_name

Example 1:
We will import the modules from the above-created package and will
use the functions inside those modules.

 Python3
from mypckg import mod1

from mypckg import mod2

mod1.gfg()

res = mod2.sum(1, 2)

print(res)

Output:
Welcome to GFG
3

You might also like