Unit 5 Python Programming (Python Packages)
Unit 5 Python Programming (Python Packages)
PYTHON PACKAGES
Modules in Python:
A module in Python is a separate file (.py file) that contains a collection of related code, such as functions,
variables, and classes, which are grouped together to perform a specific task. Instead of writing all your code
in one large file, Python allows you to divide your program into smaller parts called modules.
In simple words, you can think of a module as a code container or a toolbox. Just like a toolbox contains
different tools for different purposes, a module contains different functions and variables that you can use
whenever needed. This makes your program more organized and easier to understand.
For example, if you are working on a program that needs mathematical calculations, instead of writing all
formulas yourself, you can use the math module, which already contains useful functions like square root,
power, etc. Similarly, you can also create your own module to store commonly used functions and reuse
them in different programs.
Another important point is that modules help in code reusability and maintainability. Once you write code in
a module, you can use it multiple times in different programs without rewriting it. Also, if you need to update
or fix something, you only need to change it in one place (the module), and it will automatically reflect
everywhere it is used.
So, overall, a module is a way to organize, reuse, and manage code efficiently in Python programs.
One of the main reasons for using modules is code reusability. Instead of writing the same code again and
again, we can store it in a module and use it in different programs whenever needed. This saves time and
effort, especially in large projects.
Modules also improve code organization. When code is divided into different modules based on
functionality, it becomes more structured. For example, one module can handle calculations, another can
handle user input, and another can manage data. This makes the program neat and easier to debug.
Another important advantage is easy maintenance. If there is an error or you want to update a feature, you
only need to make changes in one module instead of the entire program. This reduces complexity and
chances of mistakes.
Modules also support teamwork and collaboration. In large projects, different developers can work on
different modules at the same time. These speeds up development and makes project management easier.
So, overall, modules are used to save time, reduce code duplication, improve readability, and make programs
easier to manage and update.
1. Built-in Modules: Built-in modules are those modules that are already available in Python by default.
You do not need to create or install them. You simply import them and use their functions. These modules
provide ready-made functionality such as mathematical operations, random number generation, date and time
handling, etc.
Example of Built-in Module:
import math
result = [Link](36)
print(result)
Output
6.0
Explanation: In this example, we used the math module, which is a built-in module in Python. The function
sqrt() is used to find the square root of a number. When we pass 36 to sqrt(), it returns 6.0. This shows how
built-in modules save time because we don’t need to write the logic ourselves.
2. User-defined Modules: User-defined modules are those modules that are created by the programmer.
When you have code that you want to reuse in multiple programs, you can store it in a separate .py file and
use it as a module.
Step 1: Create a Module:
Create a file named [Link] and write the following code:
def add(a, b):
return a + b
Step 2: Use the Module in Another File
import mymodule
result = [Link](5, 3)
print(result)
Output
8
Explanation: Here, we created our own module named mymodule. Inside it, we defined a function add() that
adds two numbers. In another file, we imported this module and used the function. When we passed 5 and 3,
it returned 8. This demonstrates how user-defined modules help in reusing code and keeping programs
organized.
1. Import the Entire Module: When you import the entire module, you bring all functions, variables, and
classes of that module into your program. To use any function, you must write the module name followed by
a dot (.) and then the function name. This method is useful when you want to use multiple features from the
same module.
2. Import Specific Functions in Python: When you import specific functions from a module, you only
bring the required function(s) into your program instead of importing the whole module. This makes your
code cleaner and more efficient, especially when you only need a few functions.
In this method, you don’t need to write the module name again and again. You can directly use the function
name.
Syntax:
from module_name import function_name
3. Import with Alias in Python: Importing with an alias means giving a short or alternative name to a
module or function while importing it. This is useful when the module name is long or when you want to
make your code shorter and easier to write.
Instead of using the original module name every time, you can use the alias name, which saves time and
improves readability.
Syntax:
import module_name as alias_name
or for specific functions:
from module_name import function_name as alias_name
def greet(name):
return "Hello " + name
Explanation:
Here, we created two functions:
add() → adds two numbers
greet() → returns a greeting message
This file is now your module.
Step 3: Import Specific Function (Optional): You can also import only required functions:
from mymodule import add
print(add(7, 3))
Output
10
Explanation: Here, we imported only the add() function, so we can directly use it without writing the
module name.
Important Points:
The module file must be in the same folder as your main program (or in Python path).
The file name becomes the module name.
You can reuse the same module in multiple programs.
def greet(name):
return "Hello " + name
def square(n):
return n * n
Step 2: Use the Module (3 Examples)
Example 1: Using add() Function
import mymodule
print([Link](4, 6))
Output
10
Explanation: We imported the module and used add() to add two numbers.
Example 2
from mymodule import greet
print(greet("Aman"))
Output
Hello Aman
Example 3
from mymodule import square
print(square(7))
Output
49
Example 2
import mymodule as mm
print([Link]("Sita"))
Output
Hello Sita
Example 3
import mymodule as mm
print([Link](6))
Output
36
Advantages of Modules in Python: Modules in Python are very useful because they help in organizing code
and making programming easier. They allow us to divide a large program into smaller parts, which improves
readability and efficiency.
1. Code Reusability: Modules allow us to reuse code again and again without rewriting it. Once a module is
created, it can be imported and used in many different programs, which saves time and effort.
2. Better Code Organization: By using modules, we can divide a large program into smaller parts based on
functionality. This makes the code clean, structured, and easier to understand.
3. Easy Maintenance: If any error or update is needed, we only need to change the specific module instead
of the whole program. This makes debugging and maintenance much easier.
4. Reduces Complexity: Modules break a big program into smaller pieces, which reduces complexity. This
helps programmers understand and manage the code more easily.
5. Supports Collaboration: In large projects, different developers can work on different modules at the
same time. This improves teamwork and speeds up development.
6. Saves Time: Since modules already contain ready-made functions (especially built-in modules),
developers don’t need to write everything from scratch. This significantly reduces development time.
Packages in Python:
A package in Python is a collection of related modules stored inside a single folder (directory). It is used to
organize large programs into smaller, manageable parts. Instead of keeping all code in one place, packages
help group similar functionalities together, making the program easier to understand and work with.
In simple terms, a package works like a folder on your computer, where modules are like files inside that
folder. This structure helps programmers keep their code neat and well-organized. Packages can also contain
sub-packages (folders inside folders), which allows creating a clear hierarchy in large projects.
The main purpose of using packages is to improve code organization, avoid confusion, and support reuse.
They make it easier to manage big projects, prevent name conflicts between modules, and allow multiple
developers to work on different parts of the same project efficiently.
A package usually contains multiple .py files (modules) and sometimes a special file called __init__.py. This
file tells Python that the directory should be treated as a package (although in modern Python versions it is
optional). Packages can also contain sub-packages, which means a package inside another package, forming
a hierarchical structure.
Packages also help in avoiding confusion and name conflicts. When different modules have similar names,
placing them in separate packages keeps them organized and easy to identify. Overall, packages make
programming more clean, efficient, and easy to maintain, especially when working on complex or large-scale
applications.
In a basic structure, a package contains multiple .py files (modules) inside a single folder. Each module
usually handles a specific task or functionality. For example, one module may handle calculations, while
another may handle user input. This separation makes the program more organized.
Explanation:
mypackage/ → This is the main folder (package)
[Link] → Contains some functions (e.g., math operations)
[Link] → Contains other functions (e.g., greetings)
[Link] → Main program where modules are used
Packages can also have a nested structure, meaning a package can contain another package inside it. This is
useful in very large projects where more organization is needed.
Explanation: Here, subpackage is a package inside mypackage. This creates a hierarchical structure, making
large programs more organized.
Example Structure:
mypackage/
__init__.py
[Link]
[Link]
Explanation:
mypackage/ → This is the main package (folder)
[Link] → Marks the folder as a package
[Link] → Contains some functions or code
[Link] → Contains other related functions
[Link]
def add(a, b):
return a + b
[Link]
def greet(name):
return "Hello " + name
Important Points:
The package folder should be in the same directory as your main file.
Module names should be valid Python file names.
You can reuse the package in multiple programs.
Types of Packages in Python: In Python, packages are mainly classified into two types based on how they
are created and used. Understanding these types helps students know how Python organizes code in different
situations.
1. Regular Packages: Regular packages are the most common type of packages in Python. These are simple
folders that contain Python modules and are used to organize code in a structured way. Traditionally, they
include a special file called __init__.py, which tells Python that the folder should be treated as a package.
These packages are easy to create and are widely used in normal Python programs. They help group related
modules together, making the code clean and easy to manage. Most beginner and intermediate-level projects
use regular packages.
Regular packages are simple folders that contain modules and are commonly used in Python programs.
Structure
mypackage/
__init__.py
[Link]
[Link]
def add(a, b):
return a + b
Main File
import mypackage.module1
print([Link](2, 3))
Output
5
Explanation: Here, mypackage is a regular package. It contains a module [Link]. We imported it and
used the add() function. This is the most common type of package used in Python.
2. Namespace Packages:
Namespace packages are a more advanced type of package. Unlike regular packages, they do not require an
__init__.py file. These packages allow Python to combine multiple directories with the same package name
into a single package.
This type is mainly used in large projects or by big organizations where different parts of a package may
exist in different locations. It provides more flexibility but is generally not required for beginners.
Namespace packages allow combining multiple folders into one package without using __init__.py.
Structure
folder1/
mypackage/
[Link]
folder2/
mypackage/
[Link]
[Link]
def add(a, b):
return a + b
[Link]
def greet(name):
return "Hello " + name
Main File
from mypackage import module1, module2
print([Link](3, 4))
print([Link]("Rahul"))
Output
7
Hello Rahul
Explanation: Here, the same package name mypackage exists in two different folders. Python combines
them into one package. This is called a namespace package and is mostly used in large or advanced projects.
Advantages of Packages in Python: Packages in Python are very useful for organizing and managing large
programs. They provide many benefits that make coding easier, cleaner, and more professional.
1. Better Code Organization: Packages help in arranging related modules into folders. This keeps the code
structured and easy to understand. Instead of mixing everything in one file, each functionality is placed in a
proper module inside a package.
2. Code Reusability: Once a package is created, it can be used in multiple programs. You don’t need to
write the same code again and again. This saves time and effort for developers.
3. Easy Maintenance: If any error occurs or updates are needed, changes can be made in a specific module
inside the package without affecting the whole program. This makes maintenance much easier.
4. Reduces Complexity: In large projects, code can become very complex. Packages divide the project into
smaller parts, making it easier to understand, manage, and debug.
5. Supports Teamwork: In real-world projects, different developers can work on different modules inside a
package at the same time. This improves teamwork and speeds up development.
6. Avoids Name Conflicts: Packages help avoid confusion when two modules have the same name. Since
they are stored in different packages, Python can easily distinguish between them.
Example:
Folder Structure:
mypackage/
__init__.py
[Link]
[Link]
def hello():
return "Hello from module1"
Using the Package
import mypackage.module1
print([Link]())
Output
Hello from module1
Important Points:
__init__.py makes a folder a Python package
It can be empty or contain initialization code
It helps Python understand how to handle imports inside the package
NumPy in Python:
NumPy (Numerical Python) is a very powerful Python library used for working with arrays and numerical
calculations. It provides support for multi-dimensional arrays and many mathematical functions, which
makes it much faster and more efficient than normal Python lists. NumPy is widely used in fields like Data
Science, Machine Learning, Artificial Intelligence, and Scientific Computing because it helps in handling
large amounts of numerical data easily.
NumPy was created by Travis Oliphant in 2005. It is an open-source project and has become one of the most
important libraries in Python. The main feature of NumPy is its ndarray (N-dimensional array), which allows
users to perform fast mathematical operations on large datasets. Unlike Python lists, NumPy arrays store data
in a more efficient way, which improves performance significantly.
The reason NumPy is so popular is because it makes complex calculations simple and fast. Operations like
addition, multiplication, mean, and matrix operations can be performed easily on entire arrays without using
loops. Because of this speed and simplicity, NumPy is considered the foundation of Data Science and
Machine Learning in Python, and almost every advanced library depends on it.
1. High Speed and Performance: NumPy is important because it performs calculations much faster than
normal Python lists. It uses a special data structure called ndarray, which is optimized for speed. This makes
NumPy very useful when working with large datasets in data science and machine learning.
2. Easy Mathematical Operations: NumPy makes mathematical calculations very simple. You can perform
operations like addition, subtraction, multiplication, division, mean, and matrix operations directly on arrays
without using loops. This reduces complexity and makes coding easier.
3. Efficient Memory Usage: NumPy uses memory in a more efficient way compared to Python lists. It
stores data in a compact form, which helps in handling large data without consuming too much memory. This
is very useful in big data applications.
4. Foundation for Data Science and AI: NumPy is the base library for many advanced Python libraries like
Pandas, TensorFlow, and Scikit-learn. Most data science and machine learning models depend on NumPy for
handling numerical data.
1. Fast Numerical Calculations: We use NumPy because it performs mathematical and numerical
operations very fast compared to normal Python lists. It is designed to handle large datasets efficiently,
which is very important in data science and machine learning.
2. Easy Handling of Arrays: NumPy makes it easy to work with arrays (1D, 2D, and multi-dimensional
data). Instead of using complex loops, we can directly perform operations on whole arrays in a simple way.
3. Supports Mathematical Functions: We use NumPy because it provides many built-in mathematical
functions like sum, mean, max, min, standard deviation, matrix operations, etc. This reduces the need to
write long code manually.
4. Memory Efficient: NumPy stores data in a compact and optimized format, which uses less memory
compared to Python lists. This helps when working with large amounts of data.
5. Base of Data Science and Machine Learning: NumPy is used because it is the foundation of many
advanced libraries like Pandas, TensorFlow, and Scikit-learn. Without NumPy, most data science and AI
work would be very difficult.
Syntax Explanation:
import numpy as np → This imports the NumPy library and gives it a short name np for easy use.
[Link]() → This function is used to create a NumPy array.
[values] → Inside these brackets, we pass multiple values (numbers) to store in the array.
arr → This is the variable where the NumPy array is stored.
NumPy Array Examples (Extra Examples): Here are some more simple and important examples to
understand NumPy better.
Syntax:
import numpy as np
arr = [Link]([values])
print(arr[index])
Explanation of Syntax
arr[index] → Used to access a specific element
Index starts from 0
0 → first element
1 → second element
and so on
Pandas in Python:
Pandas is a very important Python library used for data analysis and data manipulation. It helps us work with
structured data like tables (rows and columns), similar to Excel sheets or databases. Pandas makes it very
easy to read, clean, filter, and analyze data in Python.
Pandas was created by Wes McKinney in 2008. It is widely used in Data Science, Machine Learning,
Artificial Intelligence, and Business Analytics because it allows users to handle large datasets in a simple and
efficient way. It is built on top of NumPy, so it is very fast and powerful.
The two main data structures in Pandas are Series and DataFrame. A Series is like a single column of data,
while a DataFrame is like a complete table with rows and columns. With Pandas, we can easily perform
operations like sorting data, filtering records, reading CSV files, and analyzing information, which makes it
one of the most important tools in Python programming.
1. Series (1D Data Structure): A Series is a one-dimensional labeled array in Pandas. It is similar to a single
column in a table or Excel sheet. It can store data of any type like integers, strings, or floats. Each value in a
Series has an index number starting from 0.
Example of Series:
import pandas as pd
data = [10, 20, 30, 40]
s = [Link](data)
print(s)
Output
0 10
1 20
2 30
3 40
dtype: int64
Explanation: Here, we created a Series using a list of numbers. Pandas automatically assigns index values to
each element.
2. DataFrame (2D Data Structure): A DataFrame is a two-dimensional data structure in Pandas. It is like a
table with rows and columns, similar to an Excel sheet or database table. It is the most commonly used data
structure in Pandas.
Example of DataFrame
import pandas as pd
data = {
"Name": ["Aman", "Rahul", "Sita"],
"Age": [20, 21, 19]
}
df = [Link](data)
print(df)
Output
Name Age
0 Aman 20
1 Rahul 21
2 Sita 19
Explanation: Here, we created a DataFrame using a dictionary. It stores data in rows and columns, making
it very useful for data analysis.
Main Data Structures in Pandas (Examples): Pandas has two main data structures: Series (1D) and
DataFrame (2D). Below are 7 simple examples to understand them clearly.
Pandas Examples (Without Index Concept): Here are simple examples where we focus on data only and
do not talk about index separately.
Matplotlib in Python:
Matplotlib is a popular Python library used for data visualization, which means it helps us represent data in
the form of graphs, charts, and plots. It is mainly used to make data easy to understand visually, instead of
reading large tables or numbers. With Matplotlib, we can create different types of visual representations like
line graphs, bar charts, pie charts, histograms, and scatter plots.
Matplotlib was created by John D. Hunter. It is widely used in Data Science, Machine Learning, and Data
Analysis because it helps in understanding patterns, trends, and relationships in data quickly and clearly.
In simple words, Matplotlib converts raw data into visual form, so that users can easily analyze and make
decisions based on that data.
Why Matplotlib is Used?
1. Data Visualization: Matplotlib is used because it helps in visualizing data in graphical form like charts,
graphs, and plots. This makes data easier to understand compared to raw numbers.
2. Easy Understanding of Data: Large datasets are difficult to read, but Matplotlib converts them into
simple visuals, which helps students and analysts quickly understand patterns and trends.
3. Useful for Data Analysis: Matplotlib is widely used in Data Science and Machine Learning because it
helps in analyzing data visually, such as identifying trends, comparisons, and relationships.
4. Multiple Types of Graphs: It supports many types of graphs like:
Line graph
Bar chart
Pie chart
Histogram
Scatter plot
This flexibility makes it very powerful.
5. Better Decision Making: By showing data in visual form, Matplotlib helps in quick and better decision
making, especially in business, research, and analytics.
Explanation of Syntax:
1. import [Link] as plt
This line imports the Matplotlib library.
pyplot is a module used for creating graphs.
as plt gives a short name so we can easily use it.
2. [Link](x, y)
This function is used to create a line graph.
x represents values on the X-axis.
y represents values on the Y-axis.
It connects points and forms a graph.
3. [Link]()
This function is used to display the graph on the screen.
Without this, the graph will not appear.
Example:
import [Link] as plt
x = [1, 2, 3, 4]
y = [10, 20, 25, 30]
[Link](x, y)
[Link]()
Output: A line graph will be displayed showing the relationship between x and y values.
Explanation of Example:
x = [1, 2, 3, 4] → X-axis values
y = [10, 20, 25, 30] → Y-axis values
[Link](x, y) → creates a line graph
[Link]() → displays the graph
1. Line Graph in Matplotlib: A line graph in Matplotlib is a type of chart that is used to show the
relationship between two variables using a continuous line. It is mainly used to display trends over time, such
as growth, temperature changes, marks over months, etc.
Explanation of Syntax:
[Link](x, y) → Creates a line graph using x and y values
x → Values on X-axis (horizontal line)
y → Values on Y-axis (vertical line)
[Link]() → Displays the graph on screen
Explanation of Example:
months → X-axis values (time period)
sales → Y-axis values (data)
The line connects all points and shows growth trend
Explanation:
Days → X-axis (time)
Temperature → Y-axis (values)
marker="o" → shows each point as a circle
The graph shows the rise and fall of temperature.
This graph helps in easily understanding the weather trend.
Bar Graph in Matplotlib: A Bar Graph in Matplotlib is a type of chart that uses rectangular bars to
represent data. The height or length of each bar shows the value of the data. It is mainly used to compare
different categories easily.
Basic Syntax:
import [Link] as plt
[Link](x, y)
[Link]()
Explanation of Syntax:
[Link](x, y) → Creates a bar graph
x → Categories (like names, subjects, days)
y → Values (like marks, sales, scores)
[Link]() → Displays the graph
3. Scatter Graph in Matplotlib: A Scatter Graph (Scatter Plot) in Matplotlib is used to show the
relationship between two numerical variables. It displays data as dots (points) on a graph, where each point
represents one value pair (x, y). It is mainly used to check patterns, correlation, and distribution of data.
Basic Syntax:
import [Link] as plt
[Link](x, y)
[Link]()
Explanation of Syntax:
[Link](x, y) → Creates scatter plot
x → values on X-axis
y → values on Y-axis
[Link]() → displays the graph
Example 1: Student Study Hours vs Marks
import [Link] as plt
study_hours = [1, 2, 3, 4, 5]
marks = [40, 50, 60, 70, 85]
[Link](study_hours, marks, color="blue")
[Link]("Study Hours vs Marks")
[Link]("Study Hours")
[Link]("Marks")
[Link]()
Output: A scatter plot showing study hours vs marks relationship.
Explanation:
Each dot represents a student
More study hours → higher marks (positive relationship)
Helps to understand performance pattern
4. Pie Chart Graph in Matplotlib: A Pie Chart in Matplotlib is a circular graph that is used to show the
proportion (percentage) of different categories in a whole dataset. The circle is divided into slices, where
each slice represents a category and its value.
Basic Syntax:
import [Link] as plt
[Link](values, labels=labels)
[Link]()
Explanation of Syntax:
[Link]() → Creates a pie chart
values → numerical data (size of each slice)
labels → names of categories
[Link]() → displays the chart
5. Histogram Graph in Matplotlib: A Histogram in Matplotlib is a type of graph that is used to show the
distribution of numerical data. It divides data into intervals (called bins) and shows how many values fall into
each bin using bars.
In simple words: A histogram shows how data is spread or distributed.
Basic Syntax:
import [Link] as plt
[Link](data, bins)
[Link]()
Explanation of Syntax:
[Link]() → Creates a histogram
data → numerical values (list of numbers)
bins → number of intervals (groups of data)
[Link]() → displays the graph