KEMBAR78
Unit 2 - Modules and Packages | PDF | Python (Programming Language) | Modular Programming
0% found this document useful (0 votes)
28 views18 pages

Unit 2 - Modules and Packages

This document explains Python modules and packages, detailing their definitions, types, and how to create and import them. It covers built-in modules like 'random', 'datetime', and 'math', as well as user-defined modules and packages for organizing code. Additionally, it provides examples of using functions from these modules and the structure of Python modules and packages.

Uploaded by

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

Unit 2 - Modules and Packages

This document explains Python modules and packages, detailing their definitions, types, and how to create and import them. It covers built-in modules like 'random', 'datetime', and 'math', as well as user-defined modules and packages for organizing code. Additionally, it provides examples of using functions from these modules and the structure of Python modules and packages.

Uploaded by

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

Unit 2: Modules and Packages

2.1Built in Modules:

What is a Module in Python?


A Python module is a file consisting of Python script (generally, with a
.py extension) having definitions of functions, classes, or variables. A
module can also include runnable code.

Putting related code into a module makes it easier to read, use again in
other programs, and keep everything organized.

There are three types of modules in Python:

1.​ User-defined Modules


2.​ Built-in Modules
3.​ Third-Party Modules

Creating a Python Module


In order to create a Python module, we need to write the desire code and
save that in a file with the .py extension

​ module: calculator.py

​ # function to add two numbers
​ def add(a, b):
​ return a + b

​ # function to subtract two numbers
​ def subtract(a, b):
​ return a - b

​ # function to multiply two numbers
​ def multiply(a, b):
​ return a * b

​ # function to divide two numbers
​ def divide(a, b):
​ return a / b
Explanation:

In the above example, we have created a Python script consisting of


some functions that will help us add, subtract, multiply, and divide two
numbers. We have saved this file as calculator.py. This user-defined
module can be used in other Python programs.

2.1.1 Importing modules in python program:

Importing Module in Python


In Python, we can import the functions and classes defined in a module
to another module or the interactive interpreter. This can be used the
import statement as shown below:

Syntax:

​ import module_name
Using the import keyword followed by the module_name allow us to use
the functions defined in that module.
Note: Using the import statement, we import the whole module. In order
to access the function from the imported module, we need to use the dot .
operator.

Let us take a look at the following example where we will try to import
the user-defined module 'calculator.py' and use its functions.

Example
​ # importing the module
​ import calculator

​ # initializing some variables
​ num_1 = 16
​ num_2 = 7

​ # calling the functions of the module
​ total = calculator.add(num_1, num_2)
​ diff = calculator.subtract(num_1, num_2)
​ prod = calculator.multiply(num_1, num_2)
​ quot = calculator.divide(num_1, num_2)

​ # printing results
​ print(num_1, '+', num_2, '=', total)
​ print(num_1, '-', num_2, '=', diff)
​ print(num_1, '*', num_2, '=', prod)
​ print(num_1, '/', num_2, '=', quot)

Output:
16 + 7 = 23
16 - 7 = 9
16 * 7 = 112
16 / 7 = 2.2857142857142856
Explanation:

In this example, we have imported the user-defined module 'calculator'


and created two variables. We have then accessed the different functions
like add(), subtract(), multiply() and divide() of the 'calculator' module
and store their results in some variables. At last, we printed the results.

2.1.2 Working with Random Modules.

Python Random module


The Python Random module is a built-in module for generating random
integers in Python. These numbers occur randomly and does not follow
any rules or instructions.

We can therefore use this module to generate random numbers, display a


random item for a list or string, and so on.

The random() Function


The random.random() function gives a float number that ranges from 0.0
to 1.0. There are no parameters required for this function.

This method returns the second random floating-point value within [0.0
and 1] is returned.

Code

​ #Python program for generating random float number


​ import random
​ num=random.random()
​ print(num)
Output:
0.3232640977876686

The randint() Function


The random.randint() function generates a random integer from the
range of numbers supplied.

Code

​ # Python program for generating a random integer


​ import random
​ num = random.randint(1, 500)
​ print( num )
Output:
215

The randrange() Function


The random.randrange() function selects an item randomly from the
given range defined by the start, the stop, and the step parameters. By
default, the start is set to 0. Likewise, the step is set to 1 by default.

Code

​ # To generate value between a specific range


​ import random
​ num = random.randrange(1, 10)
​ print( num )
​ num = random.randrange(1, 10, 2)
​ print( num )
Output:
4
9

The choice() Function


The random.choice() function selects an item from a non-empty series at
random. In the given below program, we have defined a string, list and a
set. And using the above choice() method, random element is selected.

Code

​ # To select a random element


​ import random
​ random_s = random.choice('Random Module') #a string
​ print( random_s )
​ random_l = random.choice([23, 54, 765, 23, 45, 45]) #a list
​ print( random_l )
​ random_s = random.choice((12, 64, 23, 54, 34)) #a tuple
​ print( random_s )
Output:
M
765
54

The shuffle() Function


The random.shuffle() function shuffles the given list randomly.

Code
​ # To shuffle elements in the list
​ list1 = [34, 23, 65, 86, 23, 43]
​ random.shuffle( list1 )
​ print( list1 )
​ random.shuffle( list1 )
​ print( list1 )
Output:
[23, 43, 86, 65, 34, 23]
[65, 23, 86, 23, 34, 43]

2.1.3 E.g. - built-ins, time, date time, calendar, sys, etc:

Python provides various built-in functions and modules for


common tasks.

Built-ins:

These are functions and types that are always available without
needing to be imported. Examples include:
●​ print(): For outputting information to the console.
●​ len(): For getting the length of a sequence (e.g., string, list, tuple).
●​ int(), str(), float(): For type conversions.
●​ sum(): For calculating the sum of numbers in an iterable.
Modules:

Modules are files containing Python definitions and statements.


They provide a way to organize related code and can be imported
to extend the functionality of a program.
●​ time module: Provides functions for working with time, including
pausing execution (time.sleep()), getting the current time in seconds
since the epoch (time.time()), and converting time values.

Python

import time

print(time.time()) # Prints current time in seconds since the epoch

time.sleep(1) # Pauses execution for 1 second

Output:

1754561299.3362432

datetime module: Offers classes for working with dates and times in a
more structured way. It includes date, time, datetime, and timedelta
objects for representing and manipulating date and time information.

●​

Python

from datetime import datetime, date, timedelta


now = datetime.now()

print(now)

today = date.today()

print(today)

yesterday = now - timedelta(days=1)

print(yesterday)

Output:

2025-08-07 10:10:15.508656

2025-08-07

2025-08-06 10:10:15.508656

●​ calendar module: Provides functions for generating calendars,


including text-based calendars and HTML calendars.
●​

Python

import calendar

cal = calendar.month(2025, 7)

print(cal)
July 2025

Mo Tu We Th Fr Sa Su

​ 1 2 3 4 5 6

7 8 9 10 11 12 13

14 15 16 17 18 19 20

21 22 23 24 25 26 27

28 29 30 31

●​ sys module: Provides access to system-specific parameters and


functions, such as command-line arguments (sys.argv), the Python
version (sys.version), and exiting the program (sys.exit()).
●​

Python

import sys

print(sys.version)

# sys.exit() # Exits the program

2.2 User Defined functions


2.2.1 Structure of Python Modules
A Python module is simply a file containing Python code (.py file).​
It can define functions, classes, variables, and runnable code.​
Modules help organize code into manageable, reusable parts.
A Python module is a file containing Python code (definitions and
statements) that can be reused in other Python programs. It serves
as a way to organize code into logical, manageable units.

Structure of a Python Module:

A module is essentially a .py file. It can contain:

Functions: Reusable blocks of code that perform specific tasks.

Classes: Blueprints for creating objects, encapsulating data and


methods.

Variables: Data storage within the module.

Runnable Code: Code that executes when the module is run


directly (e.g., for testing or initialization). This is often placed
under an if __name__ == "__main__": block.

Import Statements:​
Modules can import other modules (built-in, standard library,
third-party, or custom) to utilize their functionalities. This is done
using the import statement.
Simple Example:

# mymodule.py

# 1. Optional module docstring

"""This module has one function to add two numbers."""

# 2. Function definition

def add(a, b):

return a + b

# 3. Main block (optional)

if __name__ == "__main__":

print(add(2, 3)) # Output: 5

Module docstring (optional)​

Function inside the module​

if __name__ == "__main__" block to run test code when


executed directly
OR

calculator.py

PI = 3.14159

def circle_area(radius):

return PI * radius * radius

class Greeter:

def __init__(self, name):

self.name = name

def greet(self):

return f"Hello, {self.name}!"


2. Make sure you're importing correctly:

python

import calculator

print(calculator.circle_area(3))

g = calculator.Greeter("Bob")

print(g.greet())

File location: Make sure calculator.py is in the same folder as your


script or notebook, or is in Python’s module search path.

2.3 Packages
A package in Python is a way to organize related modules
into a directory hierarchy.
It allows you to group modules under a common
namespace, making your code modular and easier to
manage.
●​ A package is basically a directory containing one or
more Python modules.​

●​ It must contain an __init__.py file (can be empty) to be


recognized as a package.​
2.3.1 Predefined Packages

Python’s predefined packages (standard library packages)


come installed with Python. These packages contain many
useful modules ready for you to use without additional
installation.
Examples of Predefined Packages:

●​ os — Operating system interfaces​

●​ sys — System-specific parameters and functions​

●​ math — Mathematical functions​

●​ datetime — Date and time manipulation​

●​ json — JSON serialization and deserialization​

●​ http — HTTP modules and clients​

●​ random — Generate pseudo-random numbers​

●​ re — Regular expressions​

Example:
python
import os
print("Current directory:", os.getcwd())

import math
print("Square root of 25:", math.sqrt(25))

2.3.2 User Defined Packages in Python

You can create your own packages to organize your code


into reusable modules.
How to Create a User Defined Package:

1.​ Create a directory for the package.​

2.​Add an __init__.py file inside the directory. This file can


be empty or can execute initialization code.​

3.​Add Python modules (.py files) inside the package


directory.​

4.​Import your package/modules in other scripts.​

Example Directory Structure:


markdown

mypackage/
__init__.py
module1.py
module2.py

●​ module1.py:​

python

def greet():
print("Hello from module1")

●​ module2.py:​

python

def farewell():
print("Goodbye from module2")

Using Your User Defined Package:


python

from mypackage import module1, module2

module1.greet() # Output: Hello from module1


module2.farewell() # Output: Goodbye from module2

You might also like