Modules
Modules
Advantages :
• Simplicity: Rather than focusing on the entire problem at hand, a module typically focuses on one relatively small
portion of the problem. If you’re working on a single module, you’ll have a smaller problem domain to wrap your head
around. This makes development easier and less error-prone.
• Maintainability: Modules are typically designed so that they enforce logical boundaries between different problem
domains. If modules are written in a way that minimizes interdependency, there is decreased likelihood that
modifications to a single module will have an impact on other parts of the program. This makes it more viable for a team
of many programmers to work collaboratively on a large application.
• Reusability: Functionality defined in a single module can be easily reused (through an appropriately defined interface)
by other parts of the application. This eliminates the need to recreate duplicate code.
• Scoping: Modules typically define a separate namespace, which helps avoid collisions between identifiers in different
areas of a program.
• Functions, modules and packages are all constructs in Python that promote code modularization
A file containing Python code, for e.g.: example.py, is called a module and its module name would be example. def
add(a,b):
result=a+b
return result
Here, we have defined a function add() inside a module named example. The function takes in two numbers and returns
their sum.
import example
example.add(5,5)
10
Types of Modules in Python
There are two types of Python modules: 1) In-built modules in Python 2) User-Defined
Modules in Python
1. In-built Modules in Python
The Python built-in modules come with a Python standard library, offering a range of
functionalities. So, you don’t need to install these modules separately, as they are available in
Python by default. There are several in-built Python modules, such as sys, math, os, random,
etc.
2. User-defined Modules in Python
Users create these modules to make their code more organized, modular, and reusable. These
Import Statement
are defined in Python
in a different .py file, so you must import and use them in your Python scripts.
We use the import statement in Python to import functionalities of one module to another. In
Python, you can use the functionality of one Python source file by importing its file as the module
into another source file. A single import statement allows you to import multiple modules.
However, you must load the module once, regardless of the number of times the module has been
imported into the file.
Import Modules in Python
To import modules in Python, including classes, functions, and variables, into another module,
we use the import statement in the Python source file. When the Python interpreter encounters an
import statement, it imports the module if available in the search path.
A search path refers to a list of dictionaries that the Python interpreter searches for importing a
module.
Python executes code in the module to import modules, and its contents are available for use
within the script. The separation of code into modules ensures clean and organized code.
yntax to Import a Module in Python
import module_name
This syntax is used only for importing Python modules and not for directly importing functions or
classes. To access functions within the module, we use the dot (.) operator.
Syntax
import mathutils as mt
print(mt.add(12,3))
Python Built-in Modules
Python consists of various built-in modules we can import based on our requirements. We can
use these modules for different tasks. Here are a few built-in modules in Python and their
functionalities.
Math Module in Python
This module is used for mathematical constants and functions.
Random Module in Python
The Python random module allows us to generate random numbers.
Datetime Module in Python
This module provides classes for working with date and time.
The dir() Built-in Function
The Python dir() function allows us to list all the names of the functions in a module. This
function returns a sorted list of strings containing the names defined by the module. This list
includes the names of classes, functions, and variables.
We can run the below command to get the all available modules in Python:
help('modules')
Advantages of built-in modules in Python
Reduced Development Time
Built-in modules in Python are made to perform various tasks that are used without installing
external module or writing the lengthy code to perform that specific task. So, developers used
them according to their convenience to save the time.
Optimized Performance
Some Python built-in modules are optimized for performance, using low-level code or native
bindings to execute tasks efficiently.
Reliability
These modules have been rigorously tested and have been in use by the Python community for
years. As a result, they are typically stable and have fewer bugs compared to new or less well-
known third-party libraries.
Consistency
Python Built-in modules provide consistent way to solve problems. Developers familiar with these
modules can easily understand and collaborate on codebases across different projects.
Standardization
As these modules are part of the Python Standard Library, they establish a standard way of
performing tasks.
Documentation
Python's official documentation is comprehensive and includes detailed explanations and
examples for Python built-in modules. This makes it easier to learn and utilize them.
Maintainability
Tkinter module in Python
"tkinter" is the standard GUI (Graphical User Interface) library in Python. "tkinter" module is
used to create windows, buttons, text boxes, and other UI elements for desktop applications.
Example
Firstly we imports the "tkinter" module as "tk" and defines a function, "on_button_click",
which updates a label's text. A main GUI window titled "Tkinter Example" is created,
containing a label and a button. The label displays "Click the button below", and the button,
labeled "Click Me", triggers the previously defined function when pressed. The application
remains responsive to user interactions by using the "root.mainloop()" event loop, allowing
the label's message to change upon button clicks.
import tkinter as tk
def on_button_click():
label.config(text="Hello, CSE 2B!")
root = tk.Tk()
root.title("Tkinter Example")
label = tk.Label(root, text="Click the button below")
label.pack(pady=40)
button = tk.Button(root, text="Click Me",
command=on_button_click)
button.pack(pady=40)
root.mainloop()
Random module in Python
The "random" module in Python is used to generates random numbers and provides the
functionality of various random operations such as 'random.randint()', 'random.choice()',
'random.random()', 'random.shuffle()' and many more.
Example
In the below code, firstly we import the random module, then we are printing the the random
number from "1 to 10" and random item from the list by
using random.randint() and random.choice() methods of random module respectively.
import random
num = random.randint(1, 10)
print(f"Random integer between 1 and 10: {num}")
fruits = ["Java", "C", "C++", "Python"]
chosen_fruit = random.choice(fruits)
print(f"Randomly chosen language: {chosen_fruit}")
Math Module in Python
The math module offers mathematical functions used for advanced arithmetic operations.
This includes trigonometric functions, logarithmic functions, and constants like pi and e. This
module is used to perform complex calculations using Python program.
Example
In the below example, we have used math module the find the square root of a number
using math.sqrt() method and the value of PI using math.pi method and then print the
result using print() function of Python.
import math
sqrt_val = math.sqrt(64)
pi_const = math.pi
print(sqrt_val)
print(pi_const)
datetime module in Python
The "datetime" module allows for manipulation and reading of date and time values. Some of the
basic method of "datetime" module are "datetime.date", "datetime.time",
"datetime.datetime", and "datetime.timedelta".
Example
In the below example, we have print the today' date and current time by
using datetime.date.today() method and datetime.datetime.now().time() method
ofimport
"datatime"
datetime module in Python.
date_today = datetime.date.today()
time_now = datetime.datetime.now().time()
print(date_today)
print(time_now)
OS module in Python
The "os" module in Python is used to interact with the operating system and offers OS-level
functionalities. For example, interacting with file system, reading directory, and launching
application.
Example
In the below example, we have used "os" module to fetch the directory path
using os.getcwd() method and then print the path.
import os
directory = os.getcwd()
print(directory)
calendar Module in Python
The calendar module allows operations and manipulations related to calendars.
Example
In this example, we print the October month of year 2023. Firstly, we import the "calendar" module. Generate
a string representation of October 2023 using the month() function. Print the calendar for October 2023.
import calendar
cal = calendar.month(2025,5)
print(cal)