0% found this document useful (0 votes)
8 views15 pages

Modules

The document explains the concept of modules in Python, highlighting their role in organizing code, promoting reusability, and simplifying development. It details the advantages of modular programming, types of modules (in-built and user-defined), and how to import them using various methods. Additionally, it provides examples of built-in modules like math, random, datetime, and os, along with their functionalities.

Uploaded by

task.master3402
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views15 pages

Modules

The document explains the concept of modules in Python, highlighting their role in organizing code, promoting reusability, and simplifying development. It details the advantages of modular programming, types of modules (in-built and user-defined), and how to import them using various methods. Additionally, it provides examples of built-in modules like math, random, datetime, and os, along with their functionalities.

Uploaded by

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

Modules

• Modules refer to a file containing Python statements and definitions.


• We use modules to break down large programs into small manageable and organized files. Furthermore, modules
provide reusability of code.
• We can define our most used functions in a module and import it, instead of copying their definitions into different
programs.
• Modular programming refers to the process of breaking a large, unwieldy programming task into separate, smaller,
more manageable subtasks or 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.

How to import the module is:


• We can import the definitions inside a module to another module or the Interactive interpreter in Python.
• We use the import keyword to do this. To import our previously defined module example we type the following in the
Python prompt.
• Using the module name we can access the function using dot (.) operation. For Eg:

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.

Python Import From Module


We use the from statement in Python to import specific attributes from a module, such as
functions, variables, or classes, without importing the entire module.
To import a specific function/variable/class, we use from import <class/function/variable_name>
statement. It will allow us to import a specific resource from that module.

Syntax

from <module_name> import <function_name>, <class_name>,


<function_name2>,<variable_name>
# main.py
# mathutils.py # Import everything from the mathutils module
# Functions from mathutils import *
def add(a, b):
return a + b # Using the imported functions
def subtract(a, b): print("Addition:", add(10, 5))
return a - b print("Subtraction:", subtract(10, 5))
# A list of prime numbers # Accessing the prime numbers list
prime_numbers = [2, 3, 5, 7, 11, 13, 17, 19] print("Prime Numbers:", prime_numbers)
# A dictionary of mathematical constants
constants = { # Accessing the mathematical constants
"pi": 3.14159, print("Pi:", constants["pi"])
"e": 2.71828, print("Euler's Number:", constants["e"])
"golden_ratio": 1.61803
} # Using the ComplexNumber class
# A simple class for complex numbers cn = ComplexNumber(3, 4)
class ComplexNumber: print("Complex Number:", cn)
def __init__(self, real, imag):
self.real = real Explanation:
•mathutils.py: This module contains functions, a list, a
self.imag = imag
def __str__(self): dictionary, and a class.
•main.py: Here, we import everything from the mathutils module
return f"{self.real} + {self.imag}i"
using from mathutils import *. This allows us to use the names
defined in mathutils.py directly without needing to prefix them
Import Python Standard Library Modules
The standard library in Python comprises over 200 modules that we can import based on
our requirements
# Importing modules from the Python Standard Library
import random # For generating random numbers
import math # For mathematical operations
from datetime import datetime # For date and time
manipulation

# 1. Generate a random number between 1 and 100


random_number = random.randint(1, 100)
print(f"Random Number: {random_number}")

# 2. Calculate the square root of a number


number = 16
sqrt_number = math.sqrt(number)
print(f"Square Root of {number}: {sqrt_number}")

# 3. Get the current date and time


current_datetime = datetime.now()
print(f"Current Date and Time: {current_datetime}")
Renaming the Python Module
Python allows us to change Python module names while importing it. Renaming a Python module
is an easy and flexible method. We can rename the module with the specific name and use it to
call the module resources. We use the ‘as’ keyword for renaming.
Syntax
Import Module_name as Alias_name

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)

You might also like