BCA SEM- 4 PYTHON WEBSOL UNIT - 5
Unit V
Matplotlib- plotting basic figures, subplots, line plots, bar plots, histograms, scatter plots.
Overview of Scikit-learn, SciPy, networkx. Basic Errors and Exception handling. Basic File
Handling. Applications of python
Matpoltlib is a very popular Python library for data visualization. Like Pandas, it is not
directly related to Machine Learning. It particularly comes in handy when a programmer wants to
visualize the patterns in the data. It is a 2D plotting library used for creating 2D graphs and plots. A
module named pyplot makes it easy for programmers for plotting as it provides features to control line
styles, font properties, formatting axes, etc. It provides various kinds of graphs and plots for data
visualization, viz., histogram, error charts, bar chats, etc,
Matplotlib is a plotting library for creating static, animated, and interactive visualizations in Python.
Matplotlib can be used in Python scripts, the Python and IPython shell, web application servers, and
various graphical user interface toolkits like Tkinter, awxPython, etc.
Matplotlib is a Python library which is defined as a multi-platform data visualization library built on
Numpy array. It can be used in python scripts, shell, web application, and other graphical user
interface toolkit.
Basic Line Plot:
To create a simple line plot, the [Link]() function is used. It can take one or two
arguments representing the y-axis values and optionally the x-axis values.
import [Link] as plt
import numpy as np
# Data for the plot
x = [Link]([1, 2, 3, 4, 5])
y = [Link]([2, 4, 6, 8, 10])
# Create the line plot
[Link](x, y)
# Add labels and a title
[Link]("X-axis Label")
[Link]("Y-axis Label")
[Link]("Simple Line Plot")
# Display the plot
[Link]()
Scatter Plot:
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM – 4 Page 1 |
BCA SEM- 4 PYTHON WEBSOL UNIT - 5
For a scatter plot, the [Link]() function is used, which plots individual points rather than
connecting them with lines.
import [Link] as plt
import numpy as np
# Data for the scatter plot
x_scatter = [Link]([1, 2, 3, 4, 5])
y_scatter = [Link]([5, 2, 8, 3, 7])
# Create the scatter plot
[Link](x_scatter, y_scatter)
# Add labels and a title
[Link]("X-axis")
[Link]("Y-axis")
[Link]("Simple Scatter Plot")
# Display the plot
[Link]()
Bar Plot:
Bar plots are useful for visualizing categorical data. The [Link]() function is used for this purpose.
import [Link] as plt
# Data for the bar plot
categories = ['A', 'B', 'C', 'D']
values = [10, 25, 15, 30]
# Create the bar plot
[Link](categories, values)
# Add labels and a title
[Link]("Categories")
[Link]("Values")
[Link]("Simple Bar Plot")
# Display the plot
[Link]()
subplot() Function
The subplot() function takes three arguments that describes the layout of the figure.
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM – 4 Page 2 |
BCA SEM- 4 PYTHON WEBSOL UNIT - 5
The layout is organized in rows and columns, which are represented by
the first and second argument.
With the subplot() function you can draw multiple plots in one figure:
import [Link] as plt
import numpy as np
#plot 1:
x = [Link]([0, 1, 2, 3])
y = [Link]([3, 8, 1, 10])
[Link](1, 2, 1)
[Link](x,y)
#plot 2:
x = [Link]([0, 1, 2, 3])
y = [Link]([10, 20, 30, 40])
[Link](1, 2, 2)
[Link](x,y)
[Link]()
Histogram
A histogram in Matplotlib is a graphical representation that displays the distribution of
numerical data. It groups data into intervals called "bins" and shows the frequency or count of
data points falling within each bin using bars.
A histogram is a graph showing frequency [Link] is a graph showing the number of
observations within each given interval.
Example: Say you ask for the height of 250 people, you might end up with a histogram like
this:
You can read from the histogram that there
are approximately:
2 people from 140 to 145cm
5 people from 145 to 150cm
15 people from 151 to 156cm
31 people from 157 to 162cm
46 people from 163 to 168cm
53 people from 168 to 173cm
45 people from 173 to 178cm
28 people from 179 to 184cm
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM – 4 Page 3 |
BCA SEM- 4 PYTHON WEBSOL UNIT - 5
21 people from 185 to 190cm
4 people from 190 to 195cm
Create Histogram
In Matplotlib, we use the hist() function to create [Link] hist() function will use an
array of numbers to create a histogram, the array is sent into the function as an
[Link] hist() function will read the array and produce a histogram:
import [Link] as plt
[Link]["[Link]"] = [7.50, 3.50]
[Link]["[Link]"] = True
x = [1, 2, 3,5, 1, 2, 3, 4, 1, 3, 5,5,4, 5,1]
[Link](x, orientation="vertical")
[Link]()
Scikit-learn
Scikit-learn is an open-source machine learning library that provides simple and efficient
tools for data analysis and modeling. It is built on NumPy, SciPy, and Matplotlib, making it
a powerful tool for tasks like classification, regression, clustering, and dimensionality
reduction.
Classification: Classification involves teaching a computer to categorize things. For
example, a model could be built to determine whether an email is spam or not.
Regression: Regression predicting numbers based on other numbers. For instance, a
model could predict house prices using factors like location, size, and age.
Clustering: Clustering involves finding patterns in data and grouping similar items
together. For example, customers could be segmented into different groups based on
their shopping habits.
Dimensionality Reduction: Dimensionality reduction helps focus on essential data
parts while discarding noise. This is useful when dealing with a lot of data that isn't all
relevant.
SciPy
SciPy stands for Scientific [Link] provides more utility functions for optimization, stats
and signal [Link] NumPy, SciPy is open source so we can use it [Link] was
created by NumPy's creator Travis [Link] SciPy is more focused on scientific
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM – 4 Page 4 |
BCA SEM- 4 PYTHON WEBSOL UNIT - 5
implementations, it provides many built-in scientific [Link] constants can be helpful
when you are working with Data Science.
SciPy is a Python library useful for solving many mathematical equations and algorithms. It
is designed on the top of Numpy library that gives more extension of finding scientific
mathematical formulae like Matrix Rank, Inverse, polynomial equations, LU
Decomposition, etc. Using its high-level functions will significantly reduce the complexity
of the code and helps better in analyzing the data. Key features and functionalities of SciPy
include:
Optimization: Algorithms for finding minima of functions, root finding, and curve fitting.
Integration: Numerical integration routines for various types of functions.
Interpolation: Methods for estimating values between known data points.
Linear Algebra: Advanced linear algebra operations beyond what NumPy offers, including
matrix decompositions (LU, QR, SVD, Cholesky), solving linear systems, and eigenvalue
problems.
Special Functions: A collection of mathematical functions that are commonly used in
scientific applications.
Signal Processing: Tools for analyzing and manipulating signals, including Fourier
transforms, filtering, and convolution.
Image Processing: Functions for image manipulation, filtering, and analysis.
Statistics: A comprehensive module for statistical analysis, including probability
distributions, statistical tests, and masked statistics.
Input/Output ([Link]): Functionality for reading and writing data in various scientific file
formats.
SciPy is widely used in fields such as engineering, physics, biology, and data science for
tasks requiring robust numerical computation and analysis. Its modular structure allows users
to import only the specific functions or sub-modules needed for a particular task, promoting
efficient code and resource management.
NetworkX
is a Python library designed for the creation, manipulation, and study of the structure,
dynamics, and functions of complex networks. It provides a robust set of tools for working
with graphs, which are mathematical structures used to model relationships between entities.
Key aspects and functionalities of NetworkX:
Graph Representation:
NetworkX allows the creation of various types of graphs, including:
Undirected graphs
Directed graphs (DiGraphs)
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM – 4 Page 5 |
BCA SEM- 4 PYTHON WEBSOL UNIT - 5
Multigraphs (allowing multiple edges between the same two nodes)
Weighted graphs (edges can have associated weights)
NetworkX finds applications in diverse fields such as:
Social Network Analysis: Studying connections and influence within social networks.
Biology: Analyzing biological networks like protein-protein interaction networks.
Transportation and Infrastructure: Modeling transportation networks and infrastructure
planning.
Computer Science: Analyzing web link structures, network flow, and algorithm design.
Examples of edges, or relationships between nodes, include friendships, network connections,
hyperlinks, roads, routes, wires, phone calls, emails, “likes,” payments, transactions, phone
calls, and social networking messages.
Among the principal uses of NetworkX are:
Study of the structure and dynamics of social, biological, and infrastructure networks
Standardized programming environment for graphs
Rapid development of collaborative, multidisciplinary projects
Integration with algorithms and code written in C, C++, and FORTRAN
Working with large nonstandard data sets
Errors and exception handling
Errors and exception handling in Python provide mechanisms to manage runtime issues and
prevent program crashes.
Errors are problems in a program that causes the program to stop its execution. On the other
hand, exceptions are raised when some internal events change the program's normal flow.
Errors vs. Exceptions:
Errors
typically represent issues that prevent the program from running at all, such as syntax errors
or compilation errors. These are usually beyond the scope of programmatically handling.
Exceptions
are events that occur during program execution, disrupting the normal flow. These can be
caught and handled, allowing the program to respond gracefully instead of
terminating. Examples include ZeroDivisionError, FileNotFoundError, TypeError,
and NameError
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM – 4 Page 6 |
BCA SEM- 4 PYTHON WEBSOL UNIT - 5
xception Handling with try, except, else, and finally:
try block:
This block contains the code that might raise an exception.
except block:
If an exception occurs within the try block, the corresponding except block is
executed. You can specify different except blocks to handle specific exception types
(e.g., except ZeroDivisionError:) or a generic except Exception: to catch all
exceptions. More specific exception handlers should precede more generic ones.
else block:
This optional block executes only if no exception occurs within the try block.
finally block:
This optional block always executes, regardless of whether an exception occurred or was
handled. It is commonly used for cleanup operations, such as closing files or database
connections.
Syntax Errors in Python
Syntax error occurs when the code doesn't follow Python's rules, like using incorrect
grammar in English. Python stops and points out the issue before running the program.
Example 1 : In this example, this code returns a syntax error because there is a missing
colon (:) after the if statement. The correct syntax requires a colon to indicate the start of
the block of code to be executed if the condition is true.
a = 10000
if a > 2999
print("Eligible")
Logical Errors (Exception)
Logical errors are subtle bugs in the program that allow the code to run, but produce
incorrect or unintended results. These are often harder to detect since the program doesn’t
crash, but the output is not as expected.
Common Builtin Exceptions
Some of the common built-in exceptions are other than above mention exceptions
are:
Exception Description
IndexError When the wrong index of a list is retrieved.
AssertionError It occurs when the assert statement fails
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM – 4 Page 7 |
BCA SEM- 4 PYTHON WEBSOL UNIT - 5
Exception Description
AttributeError It occurs when an attribute assignment is failed.
ImportError It occurs when an imported module is not found.
KeyError It occurs when the key of the dictionary is not found.
NameError It occurs when the variable is not defined.
MemoryError It occurs when a program runs out of memory.
It occurs when a function and operation are applied in an incorrect
TypeError
type.
Error Handling
Python provides mechanisms to handle errors and exceptions using the try, except, and
finally blocks. This allows for graceful handling of errors without crashing the program.
Syntax and Usage
Exception handling in Python is done using the try, except, else and finally blocks.
try:
# Code that might raise an exception
except SomeException:
# Code to handle the exception
else:
# Code to run if no exception occurs
finally:
# Code to run regardless of whether an exception occurs
try, except, else and finally Blocks
try Block: try block lets us test a block of code for errors. Python will "try" to execute
the code in this block. If an exception occurs, execution will immediately jump to the
except block.
except Block: except block enables us to handle the error or exception. If the code
inside the try block throws an error, Python jumps to the except block and executes it.
We can handle specific exceptions or use a general except to catch all exceptions.
else Block: else block is optional and if included, must follow all except blocks. The
else block runs only if no exceptions are raised in the try block. This is useful for code
that should execute if the try block succeeds.
finally Block: finally block always runs, regardless of whether an exception occurred or
not. It is typically used for cleanup operations (closing files, releasing resources).
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM – 4 Page 8 |
BCA SEM- 4 PYTHON WEBSOL UNIT - 5
try: try:
a=10 a=10
b=2 b=0
c=a/b c=a/b
print(c) print(c)
except: except:
print("can't divide by zero") print("can't divide by zero")
5.0 can't divide by zero
try: try:
a=10 a=10
b=2 b=0
c=a/b c=a/b
print(c) print(c)
except: except:
print("can't divide by zero") print("can't divide by zero")
else: else:
print("always enter positive value") print("always enter positive value")
5.0 can't divide by zero
always enter positive value
try: try:
a=10 a=10
b=0 b=2
c=a/b c=a/b
print(c) print(c)
except: except:
print("can't divide by zero") print("can't divide by zero")
else: else:
print("always enter positive value") print("always enter positive value")
finally: finally:
print("thanks WEBSOL") print("thanks WEBSOL")
can't divide by zero 5.0
thanks WEBSOL always enter positive value
thanks WEBSOL
Advantages of Exception Handling:
Improved program reliability: By handling exceptions properly, you can prevent your
program from crashing or producing incorrect results due to unexpected errors or input.
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM – 4 Page 9 |
BCA SEM- 4 PYTHON WEBSOL UNIT - 5
Simplified error handling: Exception handling allows you to separate error handling
code from the main program logic, making it easier to read and maintain your code.
Cleaner code: With exception handling, you can avoid using complex conditional
statements to check for errors, leading to cleaner and more readable code.
Easier debugging: When an exception is raised, the Python interpreter prints a
traceback that shows the exact location where the exception occurred, making it easier
to debug your code.
Disadvantages of Exception Handling:
Performance overhead: Exception handling can be slower than using conditional
statements to check for errors, as the interpreter has to perform additional work to catch
and handle the exception.
Increased code complexity: Exception handling can make your code more complex,
especially if you have to handle multiple types of exceptions or implement complex
error handling logic.
Possible security risks: Improperly handled exceptions can potentially reveal sensitive
information or create security vulnerabilities in your code, so it's important to handle
exceptions carefully and avoid exposing too much information about your program.
File handling
Usually, organisations would want to permanently store information about employees,
inventory, sales, etc. to avoid repetitive tasks of entering the same data. Hence, data are
stored permanently on secondary storage devices for reusability. We store Python programs
written in script mode with a .py extension.
File handling refers to the process of performing operations on a file, such as creating,
opening, reading, writing and closing it through a programming interface. It involves
managing the data flow between the program and the file system on the storage device,
ensuring that data is handled safely and efficiently.
Types of Files
Computers store every file as a collection of 0s and 1s i.e., in binary form. Therefore, every
file is basically just a series of bytes stored one after the other. There are mainly two types of
data files — text file and binary file. A text file consists of human readable characters, which
can be opened by any text editor. On the other hand, binary files are made up of non-human
readable characters and symbols, which require specific programs to access its contents.
Text file
A text file can be understood as a sequence of characters consisting of alphabets, numbers and other
special symbols. Files with extensions like .txt, .py, .csv, etc. are some examples of text files. When
we open a text file using a text editor (e.g., Notepad), we see several lines of text.
Binary Files
Binary files are also stored in terms of bytes (0s and 1s), but unlike text files, these bytes do not
represent the ASCII values of characters. Rather, they represent the actual content such as image,
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM – 4 Page 10 |
BCA SEM- 4 PYTHON WEBSOL UNIT - 5
audio, video, compressed versions of other files, executable files, etc. These files are not human
readable
Why do we need File Handling
To store data permanently, even after the program ends.
To access external files like .txt, .csv, .json, etc.
To process large files efficiently without using much memory.
To automate tasks like reading configs or saving outputs.
To handle input/output in real-world applications and tools.
Common modes include:
"r": Read mode (default). Raises an error if the file doesn't exist.
"w": Write mode. Creates the file if it doesn't exist, or truncates (empties) it if it does.
"a": Append mode. Creates the file if it doesn't exist, or adds data to the end of an existing
file.
"x": Exclusive creation mode. Creates the file, but raises an error if it already exists.
"b": Binary mode (e.g., for images, videos). Used in conjunction with other modes
(e.g., "rb", "wb").
"t": Text mode (default).
Key Concepts in Python File Handling:
Opening Files: The open() function is the primary method for interacting with files. It takes
the file name (and path, if not in the current directory) and the mode as arguments.
Writing to Files:
For writing to a file, we first need to open it in write or append mode. If we open an existing
file in write mode, the previous data will be erased, and the file object will be positioned at
the beginning of the file
write(string): Writes a string to the file write() method takes a string as an argument and
writes it to the text file. It returns the number of characters being written on single execution
of the write() method. Also, we need to add a newline character (\n) at the end of every
sentence to mark the end of line.
writelines(list_of_strings): Writes a list of strings to the file. This method is used to write
multiple strings to a file. We need to pass an iterable object like lists, tuple, etc. containing
strings to the writelines() method
Reading from Files: We can write a program to read the contents of a file. Before reading a
file, we must make sure that the file is opened in “r”, “r+”, “w+” or “a+” mode. There are
three ways to read the contents of a file:
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM – 4 Page 11 |
BCA SEM- 4 PYTHON WEBSOL UNIT - 5
read(): Reads the entire content of the file. This method is used to read a specified number
of bytes of data from a data file
readline(): Reads a single line from the file. This method reads one complete line from a
file where each line terminates with a newline (\n) character. It can also be used to read a
specified number (n) of bytes of data from a file but maximum up to the newline character
(\n).
readlines(): Reads all lines into a list of strings. The method reads all the lines and returns
the lines along with newline as a list of strings
Closing Files:
It is crucial to close files after operations to free up system resources and ensure data
integrity. The close() method is used for this.
The syntax of close() is: file_object.close()
Create File,Close file ,Open File Write
fobj=open("[Link]",'w') fobj=open("[Link]",'w')
[Link]() [Link]("hello python")
[Link]()
Write lines Read
fobj=open("[Link]",'w') fobj=open("[Link]",'r')
value=("hello python\n","hello websol\n","hello print([Link]())
bca class") [Link]()
[Link](value)
[Link]()
All Operation
fobj=open("[Link]","w") # creating a data file
name=input("Enter the name: ")
[Link](name) # Writing data to the file
[Link]() # Closing a file
print("Now reading the name from file: ")
fobj=open("[Link]","r")
#looping over the file object to read the file
for str in fobj:
print("hello "+str)
[Link]()
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM – 4 Page 12 |
BCA SEM- 4 PYTHON WEBSOL UNIT - 5
Dr. Amit Vyas sir WEBSOL 9214525215 BCA SEM – 4 Page 13 |