0% found this document useful (0 votes)
5 views31 pages

Unit 5 Python Programming (Python Packages)

This document explains the concept of Python modules and packages, emphasizing their importance in organizing, reusing, and maintaining code efficiently. It describes built-in and user-defined modules, how to import them, and the advantages of using modules for better code structure and collaboration. Additionally, it outlines the structure of packages and their role in managing larger projects by grouping related modules together.

Uploaded by

zayns8179
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)
5 views31 pages

Unit 5 Python Programming (Python Packages)

This document explains the concept of Python modules and packages, emphasizing their importance in organizing, reusing, and maintaining code efficiently. It describes built-in and user-defined modules, how to import them, and the advantages of using modules for better code structure and collaboration. Additionally, it outlines the structure of packages and their role in managing larger projects by grouping related modules together.

Uploaded by

zayns8179
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

UNIT-5

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.

Why Do We Use Modules in Python?


Modules are used in Python to make programming more simple, organized, and efficient. When we write
large programs, the code can become difficult to manage if everything is written in a single file. By using
modules, we can divide the program into smaller parts, which makes it easier to read, understand, and
maintain.

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.

Types of Modules in Python:

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.

How to Import a Module in Python:

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.

Example 1: Using math Module


import math
print([Link](25))
Output
5.0
Explanation: Here, we imported the full math module. Then we used [Link]() to find the square root of
25.

Example 2: Using math for Power


import math
print([Link](2, 3))
Output
8.0
Explanation: The [Link]() function is used to calculate power. Here, 2 raised to the power 3 gives 8.

Example 3: Using random Module


import random
print([Link](1, 10))
Output
7
Explanation: The [Link]() function generates a random number between 1 and 10. Output may
change every time you run the program.
Example 4: Using datetime Module
import datetime
print([Link]())
Output
2026-04-24
Explanation: The datetime module helps with date and time. [Link]() gives the current date.

Example 5: Using os Module


import os
print([Link]())
Output
/current/working/directory
Explanation: The [Link]() function returns the current working directory of your program.

Example 6: Using sys Module


import sys
print([Link])
Output
3.x.x (Python version)
Explanation: The [Link] shows the version of Python you are using.

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

Example 1: Import sqrt from math


from math import sqrt
print(sqrt(16))
Output
4.0
Explanation: Here, we imported only the sqrt function from the math module. So we can directly write
sqrt(16) without using [Link]().

Example 2: Import Multiple Functions


from math import sqrt, pow
print(sqrt(25))
print(pow(2, 4))
Output
5.0
16.0
Explanation: We imported two functions: sqrt and pow. Both can be used directly without writing the
module name.

Example 3: Import randint from random


from random import randint
print(randint(1, 5))
Output
3
Explanation: The randint() function generates a random number between 1 and 5. The output may be
different each time.

Example 4: Import date from datetime


from datetime import date
print([Link]())
Output
2026-04-24
Explanation: We imported only the date class from the datetime module. Then we used [Link]() to get
the current date.

Example 5: Import All Functions (Using *)


from math import *
print(sqrt(36))
print(factorial(5))
Output
6.0
120
Explanation: Using * means all functions from the module are imported. You can use them directly, but this
method is not recommended in large programs because it can create confusion if function names clash.

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

Example 1: Alias for math Module


import math as m
print([Link](49))
Output
7.0
Explanation: Here, we renamed the math module as m. Now instead of writing [Link](), we can simply
write [Link]().
Example 2: Alias for random Module
import random as r
print([Link](1, 10))
Output
6
Explanation: We used r as an alias for the random module. This makes the code shorter and easier to type.

Example 3: Alias for Specific Function


from math import sqrt as s
print(s(64))
Output
8.0
Explanation: We imported the sqrt function and renamed it as s. Now we can directly call s() instead of
sqrt().

Example 4: Multiple Functions with Alias


from math import pow as p, factorial as f
print(p(2, 5))
print(f(4))
Output
32.0
24
Explanation: We renamed pow as p and factorial as f. This helps reduce long function names.

Example 5: Alias for datetime Module


import datetime as dt
print([Link]())
Output
2026-04-24
Explanation: We used dt as a short name for the datetime module, making it easier to write and read.

Creating Your Own Module in Python:


A user-defined module is created when you write your own Python code in a separate file and reuse it in
other programs. This helps you organize code and avoid repetition.

Example: 1 Creating Your Own Module with Examples:

Step 1: Create a Module File:


First, create a new Python file with a .py extension.
For example, create a file named [Link] and write the following code:
def add(a, b):
return a + b

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 2: Import the Module in Another File:


Now create another Python file and import the module:
import mymodule
print([Link](10, 5))
print([Link]("Rahul"))
Output
15
Hello Rahul
Explanation:
 [Link](10, 5) → calls the add function → returns 15
 [Link]("Rahul") → returns "Hello Rahul"
 We use module name + dot (.) + function name to access functions.

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.

Step 4: Use Alias (Optional)


import mymodule as mm
print([Link]("Aman"))
Output
Hello Aman
Explanation: We used mm as a short name (alias) for mymodule.

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.

Example: 2 Creating Your Own Module with Examples:


A user-defined module is created when you write your own code in a separate .py file and reuse it in other
programs. This helps in code reuse and better organization.

Step 1: Create a Module File:

Create a file named [Link]:


def add(a, b):
return a + b

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: Using greet() Function


import mymodule
print([Link]("Rahul"))
Output
Hello Rahul
Explanation: We called the greet() function, which returns a greeting message.

Example 3: Using square() Function


import mymodule
print([Link](5))
Output
25
Explanation: The square() function returns the square of a number.

Step 3: Import Specific Functions (3 Examples)


Example 1
from mymodule import add
print(add(2, 3))
Output
5

Example 2
from mymodule import greet
print(greet("Aman"))
Output
Hello Aman

Example 3
from mymodule import square
print(square(7))
Output
49

Step 4: Import with Alias (3 Examples)


Example 1
import mymodule as mm
print([Link](8, 2))
Output
10

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.

Why Do We Use Packages in Python?


Packages are used in Python to organize large programs into smaller and structured parts. When a project
grows and contains many modules, it becomes difficult to manage everything in one place. By using
packages, we can group related modules together, which makes the code easier to read and understand.
Another important reason for using packages is better code management and reusability. Instead of writing
the same code again and again, we can store related modules inside a package and reuse them in different
programs. This saves time and effort, especially in large projects.

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.

Structure of a Package in Python


The structure of a package refers to how files and folders are arranged inside a package. A package is simply
a folder that contains multiple modules (Python files) organized in a proper way. This structure helps in
keeping the code clean, readable, and easy to manage, especially in large projects.

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.

Example of Package Structure:


mypackage/
[Link]
[Link]
[Link]

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.

Example of Nested Package Structure:


mypackage/
[Link]
subpackage/
[Link]

Explanation: Here, subpackage is a package inside mypackage. This creates a hierarchical structure, making
large programs more organized.

Structure of a Package in Python:


A package is simply a folder that contains important components used to organize code properly. It mainly
includes Python files (modules) and sometimes a special file called __init__.py, which helps in identifying
the folder as a package (though it is optional in modern Python).

Main Components of a Package:


Python files (modules): These are .py files that contain functions, variables, or classes. Each module usually
performs a specific task.
__init__.py file: This file is placed inside the folder to indicate that it is a package. It can also be used to run
initialization code when the package is imported.

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

Creating Your Own Package in Python (Step by Step):


Creating your own package means organizing multiple modules into a single folder so that they can be used
together in a structured way. Below are the simple steps to create and use a package.

Step 1: Create a Folder (Package):


First, create a folder that will act as your package.
For example, create a folder named mypackage.

Step 2: Create Modules Inside the Package:


Now, create Python files inside this folder.

[Link]
def add(a, b):
return a + b

[Link]
def greet(name):
return "Hello " + name

Step 3: (Optional) Create __init__.py:


You can create an empty file named __init__.py inside the folder.
This step is optional in modern Python, but it is good practice.

Step 4: Use the Package in Another File (3 Examples)

Example 1: Import Full Module


import mypackage.module1
print([Link](5, 3))
Output
8
Explanation: We imported module1 from the package and used the add() function.

Example 2: Import Specific Function


from mypackage.module2 import greet
print(greet("Rahul"))
Output
Hello Rahul
Explanation: We directly imported the greet() function from module2.

Example 3: Import with Alias


import mypackage.module1 as m1
print([Link](10, 2))
Output
12
Explanation: We used an alias m1 for module1, making the code shorter.

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.

What is __init__.py in Python?


The __init__.py file is a special Python file that is used inside a folder to tell Python that this folder should be
treated as a package. In simple words, it acts like a marker file that helps Python recognize a directory as a
package.
When Python sees __init__.py inside a folder, it understands that this folder can contain modules and can be
imported as a package. Without it (especially in older versions of Python), the folder may not be treated as a
proper package.

Why is __init__.py used?


The main purpose of __init__.py is to initialize a package. It can be empty, or it can contain code that runs
when the package is imported. It is also used to control what should be available when someone imports the
package.

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.

Why NumPy is Important?

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.

Why Do We Use NumPy?

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.

NumPy Array Syntax with Explanation:


NumPy Array Syntax
import numpy as np
arr = [Link]([values])

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:

Example 1: Simple Array:


import numpy as np
arr = [Link]([1, 2, 3, 4])
print(arr)
Output
[1 2 3 4]
Explanation: A simple 1D NumPy array is created with 4 values stored in a single variable.

Example 2: Array Addition:


import numpy as np
arr = [Link]([10, 20, 30])
print(arr + 5)
Output
[15 25 35]
Explanation: NumPy automatically adds 5 to each element using vectorized operations (no loops needed).

Example 3: Array Multiplication:


import numpy as np
arr = [Link]([2, 4, 6])
print(arr * 2)
Output
[ 4 8 12]
Explanation: Each element in the array is multiplied by 2 automatically.
Example 4: 2D Array (Matrix):
import numpy as np
arr = [Link]([[1, 2], [3, 4]])
print(arr)
Output
[[1 2]
[3 4]]
Explanation: This is a 2D array (matrix) with rows and columns, useful for mathematical and scientific
operations.

Example 5: Finding Maximum Value:


import numpy as np
arr = [Link]([5, 15, 25, 10])
print([Link](arr))
Output
25
Explanation: [Link]() returns the largest value in the array.

Example 6: Finding Mean (Average)


import numpy as np
arr = [Link]([10, 20, 30, 40])
print([Link](arr))
Output
25.0
Explanation: [Link]() calculates the average of all numbers in the array.

NumPy Array Examples (Extra Examples): Here are some more simple and important examples to
understand NumPy better.

Example 1: Finding Minimum Value


import numpy as np
arr = [Link]([8, 3, 12, 5])
print([Link](arr))
Output
3
Explanation: The [Link]() function returns the smallest value from an array.
Example 2: Sum of Elements
import numpy as np
arr = [Link]([1, 2, 3, 4])
print([Link](arr))
Output
10
Explanation: The [Link]() function calculates the total sum of all elements in an array.

Example 3: Square of Each Element


import numpy as np
arr = [Link]([2, 3, 4])
print(arr ** 2)
Output
[ 4 9 16]
Explanation: The square of each element is automatically calculated.

Example 4: Range Array (arange function)


import numpy as np
arr = [Link](1, 6)
print(arr)
Output
[1 2 3 4 5]
Explanation: The [Link]() function generates a range of numbers (from 1 to 5).

Example 5: Zeros Array


import numpy as np
arr = [Link](5)
print(arr)
Output
[0. 0. 0. 0. 0.]
Explanation: The [Link]() function creates an array in which all values are 0.

Example 6: Ones Array


import numpy as np
arr = [Link](4)
print(arr)
Output
[1. 1. 1. 1.]
Explanation: The [Link]() function creates an array in which all values are 1.

Accessing Elements in NumPy Array:

What is Accessing Elements?


Accessing elements in a NumPy array means getting specific values from the array using their position
(index). In NumPy, indexing starts from 0, just like Python lists.

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

Examples of Accessing Elements:

Example 1: Access Single Element


import numpy as np
arr = [Link]([10, 20, 30, 40])
print(arr[0])
Output
10
Explanation: Index 0 returns the first element of the array.

Example 2: Access Last Element


import numpy as np
arr = [Link]([10, 20, 30, 40])
print(arr[-1])
Output
40
Explanation: Negative index -1 gives the last element.

Example 3: Access 2D Array Element


import numpy as np
arr = [Link]([[1, 2, 3],
[4, 5, 6]])
print(arr[1, 2])
Output
6
Explanation:
1 → second row
2 → third column
So it returns value 6

Example 4: Access First Row


import numpy as np
arr = [Link]([[1, 2, 3],
[4, 5, 6]])
print(arr[0])
Output
[1 2 3]
Explanation: Index 0 returns the first row of the 2D array.

Example 5: Access Range of Elements (Slicing)


import numpy as np
arr = [Link]([10, 20, 30, 40, 50])
print(arr[1:4])
Output
[20 30 40]
Explanation: 1:4 means index 1 to 3 (4 is not included)
It returns a part of the array

 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.

Why Pandas is Used?


1. Easy Data Handling: Pandas is used because it makes working with structured data (rows and columns)
very easy. It allows users to store and manage data in a table format like Excel, which is simple to understand
and use.
2. Data Cleaning: Real-world data is often messy and incomplete. Pandas helps in removing missing values,
duplicates, and incorrect data, making the dataset clean and ready for analysis.
3. Fast Data Analysis: Pandas provides powerful tools for filtering, sorting, and analyzing data quickly.
Instead of writing long code, we can perform operations in just a few lines, which saves time.
4. Supports File Handling: Pandas can easily read and write different file formats like CSV, Excel, and
databases. This makes it very useful for working with real-world datasets.
5. Important for Data Science and Machine Learning: Pandas is widely used in Data Science, AI, and
Machine Learning because it helps in preparing and analyzing data before applying models.

Main Data Structures in Pandas


Pandas provides two main data structures that are used to store and manage data efficiently. These are Series
and DataFrame. Both are very important for data analysis and are widely used in real-world applications.

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.

Example 1: Simple 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: A simple Series is created. It stores data in a single column with index values.

Example 2: Series with Custom Index


import pandas as pd
data = [100, 200, 300]
s = [Link](data, index=["a", "b", "c"])
print(s)
Output
a 100
b 200
c 300
dtype: int64
Explanation: Here we gave custom labels (a, b, c) instead of default index numbers.
Example 3: Accessing Series Element
import pandas as pd
data = [5, 10, 15]
s = [Link](data)
print(s[1])
Output
10
Explanation: Index 1 gives the second element of Series.

Example 4: Simple 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: DataFrame stores data in table format (rows and columns).

Example 5: Access Column in DataFrame


import pandas as pd
data = {
"Name": ["Aman", "Rahul", "Sita"],
"Age": [20, 21, 19]
}
df = [Link](data)
print(df["Name"])
Output
0 Aman
1 Rahul
2 Sita
Name: Name, dtype: object
Explanation: This accesses only the "Name" column from DataFrame.

Example 6: Access Row using iloc


import pandas as pd
data = {
"Name": ["Aman", "Rahul", "Sita"],
"Age": [20, 21, 19]
}
df = [Link](data)
print([Link][1])
Output
Name Rahul
Age 21
Name: 1, dtype: object
Explanation: iloc[1] returns the second row of the DataFrame.

Example 7: Add New Column


import pandas as pd
data = {
"Name": ["Aman", "Rahul", "Sita"],
"Age": [20, 21, 19]
}
df = [Link](data)
df["Marks"] = [85, 90, 88]
print(df)
Output
Name Age Marks
0 Aman 20 85
1 Rahul 21 90
2 Sita 19 88
Explanation: A new column "Marks" is added to the DataFrame.

Pandas Examples (Without Index Concept): Here are simple examples where we focus on data only and
do not talk about index separately.

Example 1: Simple Series


import pandas as pd
data = [10, 20, 30, 40]
s = [Link](data)
print([Link])
Output
[10 20 30 40]
Explanation: Here we used .values to show only data, without showing index.

Example 2: Series Display Only Values


import pandas as pd
data = [5, 15, 25]
s = [Link](data)
print(list(s))
Output
[5, 15, 25]
Explanation: Series data is converted into a simple Python list, so only values are shown.

Example 3: DataFrame (Print Only Values)


import pandas as pd
data = {
"Name": ["Aman", "Rahul", "Sita"],
"Age": [20, 21, 19]
}
df = [Link](data)
print([Link])
Output
[['Aman' 20]
['Rahul' 21]
['Sita' 19]]
Explanation: .values removes table format and shows only data.

Example 4: Access Column Values Only


import pandas as pd
data = {
"Name": ["Aman", "Rahul", "Sita"]
}
df = [Link](data)
print(df["Name"].values)
Output
['Aman' 'Rahul' 'Sita']
Explanation: Only column data is shown without index or table structure.
Example 5: Convert DataFrame to List
import pandas as pd
data = {
"Age": [20, 21, 19]
}
df = [Link](data)
print(df["Age"].tolist())
Output
[20, 21, 19]
Explanation: .tolist() converts data into a simple Python list.

Example 6: Multiple Columns Without Index View


import pandas as pd
data = {
"Name": ["Aman", "Rahul"],
"Age": [20, 21]
}
df = [Link](data)
print([Link])
Output
[['Aman' 20]
['Rahul' 21]]
Explanation: Only raw data is shown from multiple columns.

What is index=False in Pandas?


index=False is used in Pandas when we save or export data, and we don’t want to include the index (row
numbers) in the output file or display.
Normally, Pandas automatically adds an index (0, 1, 2, …). But sometimes we don’t want these numbers,
especially when saving data to a CSV or Excel file.

Where is index=False used?


Mostly used in:
to_csv()
to_excel()
exporting data files
Example 1: Without index=False
import pandas as pd
data = {
"Name": ["Aman", "Rahul"],
"Age": [20, 21]
}
df = [Link](data)
df.to_csv("[Link]")
Output (CSV file)
,Name,Age
0,Aman,20
1,Rahul,21
Explanation: Here index (0, 1) is saved in the file.

Example 2: With index=False


import pandas as pd
data = {
"Name": ["Aman", "Rahul"],
"Age": [20, 21]
}
df = [Link](data)
df.to_csv("[Link]", index=False)
Output (CSV file)
Name,Age
Aman,20
Rahul,21
Explanation: Here index is removed, only clean data is saved.

Example 3: Printing Data (for understanding)


import pandas as pd
data = {
"Name": ["Sita", "Ravi"],
"Age": [19, 22]
}
df = [Link](data)
print(df.to_string(index=False))
Output
Name Age
Sita 19
Ravi 22
Explanation: Here index=False hides index while displaying data.

What happens when index=True in Pandas?


When index=True (or by default behavior), Pandas includes the index (row numbers) in the output file or
display. This means the data will be saved or shown along with automatic numbering like 0, 1, 2, etc.
Important point: In Pandas, index=True is actually the default setting, so you usually don’t need to write it
explicitly.

Example 1: Default behavior (index included)


import pandas as pd
data = {
"Name": ["Aman", "Rahul"],
"Age": [20, 21]
}
df = [Link](data)
df.to_csv("[Link]")
Output (CSV file)
,Name,Age
0,Aman,20
1,Rahul,21
Explanation: Index (0, 1) is automatically included because Pandas treats it as index=True by default.

Example 2: Explicit index=True


import pandas as pd
data = {
"Name": ["Sita", "Ravi"],
"Age": [19, 22]
}
df = [Link](data)
df.to_csv("[Link]", index=True)
Output
,Name,Age
0,Sita,19
1,Ravi,22
Explanation: Same result as default: index is included in the file.

Example 3: Display with index:


import pandas as pd
data = {
"Name": ["Aman", "Rahul"],
"Age": [20, 21]
}
df = [Link](data)
print(df)
Output
Name Age
0 Aman 20
1 Rahul 21
Explanation: Index is shown on the left side by default.

 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.

Basic Syntax of Matplotlib (with Explanation)


Syntax:
import [Link] as plt
[Link](x, y)
[Link]()

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

Multiple Types of Graphs:

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.

Why Line Graph is Used? We use line graphs because:


 It shows changes over time clearly
 It helps in understanding trends and patterns
 It is simple and easy to read
 It connects data points using a line
Basic Syntax:
import [Link] as plt
[Link](x, y)
[Link]()

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

Example of Line Graph:


import [Link] as plt
months = ["Jan", "Feb", "Mar", "Apr"]
sales = [100, 150, 200, 250]
[Link](months, sales)
[Link]()
Output: A line graph will be displayed showing increase in sales month by month.

Explanation of Example:
months → X-axis values (time period)
sales → Y-axis values (data)
The line connects all points and shows growth trend

Line Graph in Matplotlib (Examples)

Example 1: Student Marks in Exams


import [Link] as plt
exams = ["Test1", "Test2", "Test3", "Test4"]
marks = [60, 70, 85, 90]
[Link](exams, marks)
[Link]("Student Performance")
[Link]("Exams")
[Link]("Marks")
[Link]()
Output: A line graph showing marks increasing from Test1 to Test4.
Explanation:
 Exams → X-axis (test names)
 Marks → Y-axis (student scores)
 [Link]() → creates a line graph
 [Link]() → sets the title of the graph
 [Link]() → sets the label for the X-axis
 [Link]() → sets the label for the Y-axis
This graph clearly shows that the student’s performance is improving.

Example 2: Temperature Changes Over Days


import [Link] as plt
days = ["Mon", "Tue", "Wed", "Thu", "Fri"]
temperature = [30, 32, 31, 35, 33]
[Link](days, temperature, marker="o")
[Link]("Weekly Temperature Report")
[Link]("Days")
[Link]("Temperature (°C)")
[Link]()
Output: A line graph showing temperature changes during the week with points marked.

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.

Why Bar Graph is Used? We use bar graphs because:


 It helps in comparing data easily
 It is simple and clear to understand
 It shows differences between categories
 It is useful for students, marks, sales, surveys, etc.

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

Example 1: Student Marks Bar Graph


import [Link] as plt
students = ["Aman", "Rahul", "Sita", "Ravi"]
marks = [80, 90, 75, 85]
[Link](students, marks)
[Link]("Student Marks Comparison")
[Link]("Students")
[Link]("Marks")
[Link]()
Output: A bar graph showing different students and their marks.
Explanation:
 students → X-axis (categories)
 marks → Y-axis (values)
 Each bar shows marks of each student
 Helps to compare performance easily

Example 2: Sales Comparison


import [Link] as plt
products = ["A", "B", "C", "D"]
sales = [100, 150, 80, 200]
[Link](products, sales, color="green")
[Link]("Product Sales Report")
[Link]("Products")
[Link]("Sales")
[Link]()
Output: A bar graph showing sales of different products.
Explanation:
 Products → X-axis (categories)
 Sales → Y-axis (values)
 color="green" → sets the bar color to green
This shows which product has the highest and lowest sales.

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.

Why Scatter Graph is Used? We use scatter plots because:


 It shows relationship between two variables
 It helps to identify patterns and trends
 It is useful to find correlation (positive, negative, or no relation)
 It is widely used in Data Science and Machine Learning

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

Example 2: Temperature vs Ice Cream Sales


import [Link] as plt
temperature = [20, 25, 30, 35, 40]
sales = [100, 150, 200, 250, 300]
[Link](temperature, sales, color="red")
[Link]("Temperature vs Ice Cream Sales")
[Link]("Temperature (°C)")
[Link]("Sales")
[Link]()
Output: A scatter plot showing temperature and ice cream sales relationship.
Explanation:
 Higher temperature → more ice cream sales
 Each point shows one data pair
 Shows positive correlation

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.

Why Pie Chart is Used? We use pie charts because:


 It shows percentage distribution of data
 It helps in understanding parts of a whole
 It is very simple and visual
 It is useful in surveys, reports, and statistics

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

Example 1: Student Subject Percentage


import [Link] as plt
subjects = ["Math", "Science", "English", "Computer"]
marks = [80, 70, 60, 90]
[Link](marks, labels=subjects, autopct="%1.1f%%")
[Link]("Subject Wise Performance")
[Link]()
Output: A pie chart showing percentage distribution of marks in different subjects.
Explanation:
 marks → size of each slice
 labels → subject names
 autopct="%1.1f%%" → percentage show karta hai
 Each slice shows how much each subject contributes

Example 2: Budget Distribution


import [Link] as plt
expenses = ["Rent", "Food", "Travel", "Savings"]
amount = [40, 25, 15, 20]
[Link](amount, labels=expenses, autopct="%1.0f%%", startangle=90)
[Link]("Monthly Budget Distribution")
[Link]()
Output: A pie chart showing monthly expense distribution.
Explanation:
 Amount → percentage values
 startangle=90 → rotates the chart
 autopct → displays percentage values
 It helps to understand how money is distributed.

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.

Why Histogram is Used? We use histograms because:


 It shows data distribution clearly
 It helps to understand frequency of values
 It is useful in statistics and data analysis
 It helps to identify patterns like normal distribution, skewness, etc.

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

Example 1: Student Marks Distribution


import [Link] as plt
marks = [35, 40, 45, 50, 55, 60, 65, 70, 75, 80, 85, 90]
[Link](marks, bins=5, color="blue", edgecolor="black")
[Link]("Marks Distribution")
[Link]("Marks Range")
[Link]("Number of Students")
[Link]()
Output: A histogram showing how students’ marks are distributed in different ranges.
Explanation:
 Marks → data set
 bins=5 → divides the data into 5 groups
 edgecolor="black" → sets the bar borders to black
 It shows how many students fall into each marks range.

Example 2: Age Distribution


import [Link] as plt
ages = [18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29]
[Link](ages, bins=4, color="green", edgecolor="black")
[Link]("Age Distribution")
[Link]("Age Groups")
[Link]("Frequency")
[Link]()
Output: A histogram showing how ages are distributed in groups.
Explanation:
 Ages → input data
 bins=4 → divides the data into 4 age groups
 It shows how many people are in each age range.

You might also like