# Module in Python

Sign up for FREE 1 month of Kindle and read all our books for free.

Get FREE domain for 1st year and build your brand new site

A module in Python is a library which is a collection of various utilities/ functions which can be loaded in external Python code and used accordingly. For example: One module in Python is **string** which is extensively used for handling strings. Note that the same operations can be done with the module but will take more time to implement as all basic operations need to be supported.

One can think of this as header files in C/ C++ or libraries in Java. The advantage of modules in Python is that one can **import a small part of the module** as well which is not possible in all languages like Java and C++.

Module is a python code (saved as '.py' file) and generally have definition of classes, variables, constants and functions. A module can be access by using import function. Anyone can create modules or can use the modules which are present by default called as built-in modules. The general attribute of module in python is given as below,

```
module.function (argument if any)
```

For creating a module we just have to first create a text file then save it using .py extention. This module can be access by typing the following commands in the python interpreter,

```
>>> import module
```

Here the word module in the command will be the file name which we want to access. We will cover the following points:

- Prominent built-in modules in Python
- Custom Python module
- 3 built-in modules: os, random, math

# Prominent built-in modules in Python

**builtin**: This module contains built-in functions which are automatically available in all Python modules. You usually do not have to import this module; it is loaded automatically when the interpreter starts.**exceptions**: This module provides the standard exception hierarchy. It is automatically imported when Python starts. An exception is an event that occurs during the execution of a program and disrupts the normal flow of the program's instructions. An exception is a Python object that represents an error.**os**: This module provides a unified interface to a number of operating system functions.**string**: This module contains a number of functions for string processing.**re**: This module provides a set of powerful regular expression facilities. A Regular Expression (RegEx) allows powerful string search and matching for a pattern in a string.**math**: This module implements a number of mathematical operations for floating point numbers. These functions are generally thin wrappers around the platform C library functions.**cmath**: This module contains a number of mathematical operations for complex numbers.**sys**: This module provides functions and variables used to manipulate different parts of the

Python runtime environment.**time**: This module provides functions to deal with dates and the time within a day. It wraps the C runtime library.**gc**: This module provides an interface to the built-in garbage collector.

# Custom Python module

Now,lets learn to create a module of our own and run it with python interpreter. Here we have written a python code for welcome as well as for calculating the average of 3 numbers using functions and saved the file with name *welcome.py*. After saving the file for accessing our module, type >>>**import filename** in the IDLE, in our case the file name is welcome, so we will give command as >>>import welcome. This will import our python code.

```
def Hello(name):
print("Hello {}. Welcome to Opengenus Internship task.".format(name))
return
you=input('Enter your name')
Hello(you)
def average(num1,num2,num3):
return((num1+num2+num3)/3)
```

For executing the function within the code the syntax is:

```
filename.functionname()
```

In our case the function name is *average*, So the command will be

```
welcome.average(10,20,30)
```

This is how anyone can create a module of their own choice in python.

Output:

```
>>>import welcome
Enter your name Gaurav
Hello Gaurav. Welcome to Opengenus Internship task.
>>>welcome.average(10,20,30)
20.0
```

We will now learn more about three modules in python which are os, random and math.

# os module

Functions in os module are used for performing operating system related tasks such as creating a directory, changing its path, listing the content in the directory and removing a directory. Some commonly used functions in th os module are,

a. mkdir() - Create a directory

b. chdir() - Change current working directory

c. getwd() - Get the current working directory

d. rmdir() - Remove directory

e. listdir() -List the content of current directory

Note: For using any module in python first import that module using python interpreter.

Here we have import the os module, we have created a directory using mkdir function of os module. we have changed the current directory using function in module.

```
>>>import os
>>>os.mkdir("d:\\opengenus")
>>>os.chdir("d:\\opengenus")
>>>os.getcwd()
'd:\\opengenus'
>>>os.listdir("d:\\opengenus")
['Article1','Article2','Article3']
>>>
```

For removing a directory we first have to change the current working directory, as we can not remove the directory on which we are working.

```
>>> os.rmdir("d:\\opengenus")
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
os.rmdir("d:\\opengenus")
PermissionError: [WinError 32] The process cannot access the file because it is being used by another process: 'd:\\opengenus'
>>> os.chdir("d:\\")
>>> os.getcwd()
'd:\\'
>>> os.rmdir("d:\\opengenus")
>>>
```

# random module

Function in random module depend on the sudo random number generator function random.Some common functions of this modules are as below,

a. random() - This function generates a random float number between o.o to 1.0

b. randint() - This function returns a random integer between the specified integer.

c. randrange() - It returns a randomly selected element from the range which have variables such as start, stop and step.

d. choice() - Retuens a randomply selected element from the non-empty sequence.

e. shuffle() - This randomly reorders element in the list.

```
>>> import random
>>> random.random()
0.09070970043752291
>>> random.randrange(10,60,5)
20
>>> random.randint(5,15)
6
>>> random.choice("algorithm")
'l'
>>> numbers=[10,20,30,40,50]
>>> random.shuffle(numbers)
>>> numbers
[30, 50, 20, 10, 40]
>>> random.choice(numbers)
40
>>>
```

# math module

This module in python defines some constants as well as functions such as logarithmic, trigonometric and represenation. These are explained below,

a. Constants:

The math module defines two constants such as pi and euler's number.

```
>>> import math
>>> math.pi
3.141592653589793
>>> math.e
2.718281828459045
>>>
```

b. Trigonometric function:

This function is used for trigonometric ratios for given angle. The trigonometric function need radians as an argument. So the function degrees and radians are used here. Similarly for getting sine and cosine angles, first we convert it in 30 radians and then use the function.

```
>>> import math
>>> math.radians(180)
3.141592653589793
>>> math.degrees(3*math.pi)
540.0
>>> math.radians(30)
0.5235987755982988
>>> math.sin(math.radians(30))
0.49999999999999994
>>> math.cos(math.radians(30))
0.8660254037844387
>>> math.tan(math.radians(30))
0.5773502691896257
>>>
```

c. Logarithmic function:

This function contains log function, power function, exponential function, square root function etc.

```
>>> import math
>>> math.log(20)
2.995732273553991
>>> math.log10(32)
1.505149978319906
>>> math.log10(100)
2.0
>>> math.exp(5)
148.4131591025766
>>> math.pow(3,5)
243.0
>>> math.sqrt(144)
12.0
>>> math.sqrt(625)
25.0
>>>
```

d. Representation function:

This function contains ceil and floor function. The ceil function round off the floating integer to smallest greater than or equal integer, also the floor function returns the largest smaller than or equal integer to the given floating number.

```
>>> import math
>>> math.ceil(7.2)
8
>>> math.ceil(7.9)
8
>>> math.floor(15.4)
15
>>> math.floor(15.8)
15
>>>
```

This is how the modules are used for arranging the python code. These modules makes the task simpler as well as saves time.