Py New U5
Py New U5
1.Syntax Errors:
Syntax errors occur when the code violates the rules of the Python language. These errors are typically raised
during the parsing phase before the code is executed. Common causes of syntax errors include missing colons,
mismatched parentheses, incorrect indentation, etc. Examples of syntax errors:
print("Hello, World!"
if x > 5
Runtime errors, also known as exceptions, occur during the execution of a program when something unexpected
happens. These errors are not caught during the parsing phase and are raised when a specific condition or
operation cannot be performed as expected. Common examples of runtime errors include division by zero,
accessing an index that is out of range, trying to open a file that does not exist, etc.
x = 10 / 0
my_list = [1, 2, 3]
print(my_list[5])
Semantic errors, also known as logic errors, do not raise any errors or exceptions, but they cause the program to
produce incorrect or unexpected results due to logical flaws in the code. These errors are challenging to identify
as they do not generate any error messages. They arise when the programmer makes a mistake in the algorithm
or the logical flow of the program.
sum = 0
for i in range(10):
● In general, when a Python program encounters a situation that it cannot cope with, it raises an
exception.
● When an exception has occurred, it must either handle the exception otherwise it terminates the
execution.
● The Python programming language provides three keywords to handle the exceptions.
✔ try
✔ except
✔ finally
try
● The try keyword is used to define a block of code which may cause an exception.
except
● The except keyword is used to define a block of code which handles the exception.
finally
● The finally keyword is used to define a block of code which is to execute, regardless of an exception
occurrence.
The Python allows us to use an optional else keyword that can be used with try block. The else is used to define
a block of code to be executed if no exception were raised.
Syntax
try:
except:
finally:
Example
try:
a = a * 10
print(a)
except:
finally:
Output:
● In such a case, it handles only the particularized exception, if any other exception occurs it terminates the
execution.
try:
c=a/b
print('Result: ', c)
except ZeroDivisionError:
Output:
Enter a number: 10
Enter a number: 0
1. ZeroDivisionError
try:
result = 10 / 0
except ZeroDivisionError as e:
print("Caught ZeroDivisionError:", e)
O/P:
try:
num = int("abc")
except ValueError as e:
print("Caught ValueError:", e)
O/P:
Caught ValueError: invalid literal for int() with base 10: 'abc'
3. TypeError
try:
num = "123" + 456
except TypeError as e:
print("Caught TypeError:", e)
O/P:
●In Python, the except block may also catch multiple exceptions. In such a case, a single try block has multiple
except blocks.
●When an exception arises, it sent to the first except block if it can handle then rest of the except blocks are
ignored otherwise it forwarded to the next except block and so on.
●The above example code may generate two types of exceptions ZeroDivisionError and ValueError.
1.
try:
c=a/b
print('Result: ', c)
except ZeroDivisionError:
except ValueError:
else:
Enter a number: a
try:
result = a / b
return result
except Exception as e:
finally:
try:
result1 = divide_numbers(10, 2)
result2 = divide_numbers(10, 0)
except Exception as e:
O/P:
Result 1: 5.0
Result 2: None
Caught a specific exception: unsupported operand type(s) for /: 'int' and 'str'
try:
number = int(input_str)
return number
except ValueError as e:
try:
result1 = convert_to_integer("123")
result2 = convert_to_integer("abc")
except Exception as e:
O/P:
Result 1: 123
Error: invalid literal for int() with base 10: 'abc'. Invalid input value!
Result 2: None
class MyCustomException(Exception):
pass
def check_value(value):
if value < 0:
else:
try:
check_value(10)
check_value(-5)
except MyCustomException as e:
O/P
In this example, we define a custom exception class MyCustomException, which inherits from the built-in
Exception class. We also create a function check_value that takes a value as input and raises MyCustomException
if the value is negative.
When we call check_value(10), no exception is raised because the value is positive. However, when we call
check_value(-5), the MyCustomException is raised, and the exception is caught by the except
MyCustomException block, which then prints "Custom exception caught: Value cannot be negative."
Lab-Program Week 10
1.Write a program which repeatedly reads numbers until the user enters ‘done’. Once ‘done’ is entered, print out
the total, count and average of the numbers. If the user enters anything other than a number, detect the Error
using try and except blocks, and print an error message, skip to the next number.
total = 0
count = 0
while True:
if user_input.lower() == 'done':
break
else:
try:
number = float(user_input)
total += number
count += 1
except ValueError:
if count > 0:
print(f"Total: {total}")
print(f"Count: {count}")
print(f"Average: {average}")
else:
pass
O/P:
Total: 15.0
Count: 5
Average: 3.0
Files
●Files are named locations on disk to store related information. They are used to permanently store data in a
non-volatile memory (e.g. hard disk).
●Since Random Access Memory (RAM) is volatile (which loses its data when the computer is turned off), we use
files for future use of the data by permanently storing them.
●When we want to read from or write to a file, we need to open it first. When we are done, it needs to be closed
so that the resources that are tied with the file are freed.
✔ Open a file
●Python has a built-in open() function to open a file. This function returns a file object, also called a handle, as
it is used to read 0or modify the file accordingly.
Example
●We can specify the mode while opening a file. In mode, we specify whether we want to read r, write w or
append a to the file.
●We can also specify if we want to open the file in text mode or binary mode.
●The default is reading in text mode. In this mode, we get strings when reading from the file.
●On the other hand, binary mode returns bytes and this is the mode to be used when dealing with non-text files
like images or executable files.
Mode Description
w Opens a file for writing. Creates a new file if it does not exist or truncates the file if it exists.
x Opens a file for exclusive creation. If the file already exists, the operation fails.
Opens a file for appending at the end of the file without truncating it. Creates a new file if it
a
does not exist.
●When working w
ith files in text mode, it is highly recommended to specify the encoding type.
Example
●Closing a file will free up the resources that were tied with the file. It is done using the close() method available
in Python.
●Python has a garbage collector to clean up unreferenced objects but we must not rely on it to close the file.
f.close()
●This method is not entirely safe. If an exception occurs when we are performing some operation
with the file, the code exits without closing the file.
●A safer way is to use a try...finally block.
Example
try:
f = open("test.txt", encoding = 'utf-8')
# perform file operations
finally:
f.close()
●The best way to close a file is by using the with statement. This ensures that the file is closed when
the block inside the with statement is exited.
●We don't need to explicitly call the close() method. It is done internally.
Example
with open("test.txt", encoding = 'utf-8') as f:
pass
Writing to Files
●In order to write into a file in Python, we need to open it in write w, append a or exclusive creation x mode.
●We need to be careful with the w mode, as it will overwrite into the file if it already exists. Due to this, all the
previous data are erased.
●Writing a string or sequence of bytes (for binary files) is done using the write() method. This method returns
the number of characters written to the file.
Example
f.write("This file\n\n")
●This program will create a new file named test.txt in the current directory if it does not exist. If it does exist, it
is overwritten.
●We must include the newline characters ourselves to distinguish the different lines.
Reading Files
●To read a file in Python, we must open the file in reading r mode.
●There are various methods available for this purpose. We can use the read(size) method to read in the size
amount of data. If the size parameter is not specified, it reads and returns up to the end of the file.
●We can read the text.txt file we wrote in the above section in the following way:
Example
f = open("D:/python/cse-files/test.txt",'r',encoding = 'utf-8')
O/P:
my f
irst
file
This file
●We can see that the read() method returns a newline as '\n'. Once the end of the file is reached, we get an
empty string on further reading.
●We can change our current file cursor (position) using the seek() method. Similarly, the tell() method returns
our current position (in number of bytes).
Example
f = open("D:/python/cse-files/test.txt",'r',encoding = 'utf-8')
O/P:
my f
irst
file
This file
50
my first file
This file
●We can read a file line-by-line using a for loop. This is both efficient and fast.
f = open("D:/python/cse-files/test.txt",'r',encoding = 'utf-8')
for line in f:
O/P:
my first file
This file
●In this program, the lines in the file itself include a newline character \n. So, we use the end parameter of the
print() function to avoid two newlines when printing.
●Alternatively, we can use the readline() method to read individual lines of a file. This method reads a file till the
newline, including the newline character.
readline()
The readline() method returns one line from the file.
You can also specify how many bytes from the line to return, by using the size parameter.
Syntax
file.readline(size)
f = open("D:/python/cse-files/test.txt", "r")
print(f.readline())
print(f.readline())
O/P
my first file
File Positions
seek() method
In Python, seek() function is used to change the position of the File Handle to a given specific position. File handle
is like a cursor, which defines from where the data has to be read or written in the file.
Parameters:
The reference point is selected by the from_what argument. It accepts three values:
0: sets the reference point at the beginning of the file
Note: Reference point at current position / end of file cannot be set in text mode except when offset is equal to
0.
Example1
f = open("D:/python/cse-files/test.txt", "r")
f.seek(20)
print(f.tell())
print(f.readline())
f.close()
O/P:
20
Example2
f = open("D:/python/cse-files/test1.txt", "rb")
f.seek(-10, 2)
print(f.tell())
# printing
print(f.readline().decode('utf-8'))
f.close()
O/P:
50
its bad.'
2. Write a python script to perform file operations (creating, open, read and write-use exception
handling)
def create_file(file_name):
try:
with open(file_name, 'x'): # 'x' mode opens the file for exclusive creation, raises FileExistsError if the file
already exists
except FileExistsError:
try:
file.write(data + "\n")
except FileNotFoundError:
except Exception as e:
def read_file(file_name):
try:
content = file.read()
print("File content:")
print(content)
except FileNotFoundError:
except Exception as e:
create_file(file_name)
write_to_file(file_name, data_to_write)
read_file(file_name)
if __name__ == "__main__":
main()
O/P:
Enter data to write to the file: coding is interesting but difficult to explain
File content:
PIP, short for "Python Package Index," is a package manager used to install and manage Python packages. It
allows you to easily install, upgrade, and uninstall Python libraries and dependencies from the Python Package
Index or other repositories.
Step 2: Check if PIP is installed on your system. Type the following command and press Enter:
pip –version
This command will display the version of PIP installed on your system if it is available. If PIP is not installed, you'll
need to install it first. However, in most cases, if you're using a recent version of Python, PIP comes bundled by
default.
If PIP is not installed or you are using an older version of Python, you can follow these steps to install PIP:
First Way
Step 1: Download get-pip.py: Open your web browser and visit the official "get-pip.py" script link:
https://bootstrap.pypa.io/get-pip.py. Right-click on the page and choose "Save Page As" or "Save Link As" to
download the file. Save it in a location you can easily access, such as your Downloads folder.
Step2:
python3 get-pip.py
Second Way
If you do not have PIP installed, you can download and install it from this page: https://pypi.org/project/pip/
What is a Package?
Modules are Python code libraries you can include in your project.
my_package/
__init__.py
module1.py
module2.py
Let's say you want to install the requests library, which is commonly used for making HTTP requests in Python.
To install it, use the following command
import camelcase
c = camelcase.CamelCase()
txt = "hello world"
print(c.hump(txt))
O/P:
Hello World
Remove a Package
uninstall <package-name>
List Packages
pip list
Numpy
NumPy is a Python library. NumPy is used for working with arrays. NumPy is short for "Numerical Python". It also
has functions for working in domain of linear algebra, Fourier transform, and matrices.
NumPy was created in 2005 by Travis Oliphant. It is an open-source project and you can use it freely.
NumPy aims to provide an array object that is up to 50x faster than traditional Python lists.
The array object in NumPy is called ndarray, it provides a lot of supporting functions that make working with
ndarray very easy.
Arrays are very frequently used in data science, where speed and resources are very important.
This is the main reason why NumPy is faster than lists. Also, it is optimized to work with latest CPU architectures.
NumPy is a Python library and is written partially in Python, but most of the parts that require fast
computation are written in C or C++.
Installation of NumPy
If you have Python and PIP already installed on a system, then installation of NumPy is very easy.
If this command fails, then use a python distribution that already has NumPy installed like, Anaconda, Spyder
etc.
Import NumPy
Once NumPy is installed, import it in your applications by adding the import keyword:
import numpy
Example
import numpy
print(arr)
O/P:
[1 2 3 4 5]
NumPy as np
NumPy is usually imported under the np alias.
alias: In Python alias are an alternate name for referring to the same thing.
import numpy as np
import numpy as np
print(arr)
O/P:
[1 2 3 4 5]
print(arr)
print(type(arr))
Output:
[1,2,3,4,5]
<class ‘numpy.ndarray’>
Example2:
import numpy as np
Output:
[1,2,3,4,5]
Dimensions in Arrays
0-D Arrays
0-D arrays, or Scalars, are the elements in an array. Each value in an array is a 0-D array.
Example
Create a 0-D array with value 42
import numpy as np
arr = np.array(42)
print(arr)
Output:
42
1-D Arrays
An array that has 0-D arrays as its elements is called uni-dimensional or 1-D array.
These are the most common and basic arrays.
Example
Create a 1-D array containing the values 1,2,3,4,5:
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Output:
[1, 2, 3, 4, 5])
2-D Arrays
An array that has 1-D arrays as its elements is called a 2-D array.
NumPy has a whole sub module dedicated towards matrix operations called numpy.mat
Example
Create a 2-D array containing two arrays with the values 1,2,3 and 4,5,6:
import numpy as np
print(arr)
Output:
[[1,2,3]
[4,5,6]]
3-D arrays
An array that has 2-D arrays (matrices) as its elements is called 3-D array.
Example
Create a 3-D array with two 2-D arrays, both containing two arrays with the values 1,2,3 and 4,5,6:
import numpy as np
print(arr)
Output:
[[[1,2,3]
[4,5,6]]
[[1,2,3]
4,5,6]]]
import numpy as np
a = np.array(42)
b = np.array([1, 2, 3, 4, 5])
c = np.array([[1, 2, 3], [4, 5, 6]])
d = np.array([[[1, 2, 3], [4, 5, 6]], [[1, 2, 3], [4, 5, 6]]])
print(a.ndim)
print(b.ndim)
print(c.ndim)
print(d.ndim)
O/P:
3
Slicing arrays
Slicing in python means taking elements from one given index to another given index.
Example1
import numpy as np
print(arr[1:5])
O/P:
[2 3 4 5]
Example2
import numpy as np
print(arr[4:])
O/P:
[5 6 7]
Example3
import numpy as np
print(arr[:4])
O/P:
[1 2 3 4]
Example4
import numpy as np
Negative Slicing
import numpy as np
print(arr[-3:-1])
O/P:
[5 6]
Below is a list of all data types in NumPy and the characters used to represent them.
• i - integer
• b - boolean
• u - unsigned integer
• f - float
• c - complex float
• m - timedelta
• M - datetime
• O - object
• S - string
• U - unicode string
import numpy as np
print(arr.dtype)
O/P:
int32
Example2
import numpy as np
print(arr.dtype)
O/P:
<U6
print(arr)
O/P:
[1 2 3 4 5 6]
import numpy as np
print(arr)
O/P:
[[1 2 5 6]
[3 4 7 8]]
import numpy as np
print(arr)
O/P:
[[1 2]
[3 4]
[5 6]
[7 8]]
Example1:
import numpy as np
newarr = np.array_split(arr, 3)
print(newarr)
O/P:
Example2:
import numpy as np
newarr = np.array_split(arr, 3)
print(newarr)
O/P:
Example3:
import numpy as np
newarr = np.array_split(arr, 2)
print(newarr)
O/P:
Searching Arrays
To search an array, use the where() method.
Find the indexes where the value is 4:
import numpy as np
x = np.where(arr == 4)
print(x)
O/P:
Sorting Arrays
The NumPy ndarray object has a function called sort(), that will sort a specified array.
import numpy as np
print(np.sort(arr))
O/P:
[0 1 2 3]
Iterating Arrays
import numpy as np
for x in arr:
print(x)
O/P:
3
The Difference Between Copy and View
The main difference between a copy and a view of an array is that the copy is a new array, and the view is just a
view of the original array.
The copy owns the data and any changes made to the copy will not affect original array, and any changes made
to the original array will not affect the copy.
The view does not own the data and any changes made to the view will affect the original array, and any changes
made to the original array will affect the view.
COPY
import numpy as np
arr[0= = 42
print(arr)
print(x)
O/P:
[42 2 3 4 5]
[1 2 3 4 5]
VIEW
import numpy as np
x = arr.view()
arr[0] = 42
print(arr)
print(x)
O/P:
[42 2 3 4 5]
[42 2 3 4 5]
Shape of an Array
NumPy arrays have an attribute called shape that returns a tuple with each index having the number of
corresponding elements.
import numpy as np
print(arr.shape)
O/P:
(2, 4)
newarr = arr.reshape(4, 3)
print(newarr)
O/P:
[[ 1 2 3]
[ 4 5 6]
[ 7 8 9]
[10 11 12]]
Shuffling Arrays
from numpy import random
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
random.shuffle(arr)
print(arr)
Output:
[2 1 5 4 3]
Computers work on programs, and programs are definitive set of instructions. So it means there must be some
algorithm to generate a random number as well.
If there is a program to generate random number it can be predicted, thus it is not truly random.
Random numbers generated through a generation algorithm are called pseudo random.
Yes. In order to generate a truly random number on our computers we need to get the random data from some
outside source. This outside source is generally our keystrokes, mouse movements, data on network etc.
We do not need truly random numbers, unless its related to security (e.g. encryption keys) or the basis of
application is the randomness (e.g. Digital roulette wheels).
Example
x = random.randint(100)
print(x)
Output:
28
Matrix Addition
import numpy as np
print("Matrix 1:")
print(matrix1)
print("\nMatrix 2:")
print(matrix2)
print(result)
O/P:
Matrix 1:
[[1 2]
[3 4]]
atrix 2:
[[5 6]
[7 8]]
[[ 6 8]
[10 12]]
Matrix Multiplication
import numpy as np
print("Matrix 1:")
print(matrix1)
print("\nMatrix 2:")
print(matrix2)
print(result_dot)
print(result_operator)
O/P:
Matrix 1:
[[1 2]
[3 4]]
Matrix 2:
[[5 6]
[7 8]]
[[19 22]
[43 50]]
[[19 22]
[43 50]]
Pandas
What is Pandas?
Pandas is a Python library used for working with data sets. It has functions for analyzing, cleaning, exploring, and
manipulating data.The name "Pandas" has a reference to both "Panel Data", and "Python Data Analysis" and was
created by Wes McKinney in 2008.
Use of Pandas
Pandas allows us to analyze big data and make conclusions based on statistical theories.
Pandas can clean messy data sets, and make them readable and relevant.
• Max value?
• Min value?
Pandas are also able to delete rows that are not relevant, or contains wrong values, like empty or NULL values.
This is called cleaning the data.
Installation of Pandas
If you have Python and PIP already installed on a system, then installation of Pandas is very easy.
If this command fails, then use a python distribution that already has Pandas installed like, Anaconda, Spyder
etc.
Import Pandas
Once Pandas is installed, import it in your applications by adding the import keyword:
import pandas
Example
1:
import pandas
mydataset = {
'passings': [3, 7, 2]
myvar = pandas.DataFrame(mydataset)
print(myvar)
O/P:
cars passings
0 BMW 3
1 Volvo 7
2 Ford 2
What is a DataFrame
A Pandas DataFrame is a 2-dimensional data structure, like a 2-dimensional array, or a table with rows and
columns.
Example
import pandas as pd
data = {
df = pd.DataFrame(data)
print(df)
O/P:
calories duration
0 420 50
1 380 40
2 390 45
Pandas Series
What is a Series?
A Pandas Series is like a column in a table.It is a one-dimensional array holding data of any type.
Example
import pandas as pd
a = [1, 7, 2]
myvar = pd.Series(a)
print(myvar)
O/P:
0 1
1 7
2 2
dtype: int64
Create Labels
With the index argument, you can name your own labels.
import pandas as pd
a = [1, 7, 2]
print(myvar)
O/P:
x 1
y 7
z 2
dtype: int64
Example
import pandas as pd
df = pd.read_csv('D:/python/cse-files/venev/data1.csv')
# For example, you can print the first few rows using the 'head()' method:
print(df.head())
O/P:
[5 rows x 20 columns]
The head() method returns the headers and a specified number of rows, starting from the top.
Example
import pandas as pd
df = pd.read_csv('D:/python/cse-files/venev/data1.csv')
print(df.head(10))
O/P:
There is also a tail() method for viewing the last rows of the DataFrame.
The tail() method returns the headers and a specified number of rows, starting from the bottom.
Example
import pandas as pd
df = pd.read_csv('D:/python/cse-files/venev/data1.csv')
print(df.tail(5))
O/P:
[5 rows x 20 columns]
SciPy
SciPy is a scientific computation library that uses NumPy underneath.
It provides more utility functions for optimization, stats and signal processing.
SciPy has optimized and added functions that are frequently used in NumPy and Data Science.
Installation of SciPy
If you have Python and PIP already installed on a system, then installation of SciPy is very easy.
If this command fails, then use a Python distribution that already has SciPy installed like, Anaconda, Spyder etc.
import scipy
print(scipy.__version__)
Import SciPy
Once SciPy is installed, import the SciPy module(s) you want to use in your applications by adding the from scipy
import module statement.
Now we have imported the constants module from SciPy, and the application is ready to use it
Constants
As SciPy is more focused on scientific implementations, it provides many built-in scientific constants.
These constants can be helpful when you are working with Data Science.
Example1
print(constants.liter)
O/P:
0.001
constants: SciPy offers a set of mathematical constants, one of them is liter which returns 1 liter as cubic
meters.
Example2
print(constants.pi)
O/P:
3.141592653589793
Time:
print(constants.minute) #60.0
print(constants.hour) #3600.0
print(constants.day) #86400.0
print(constants.week) #604800.0
print(constants.year) #31536000.0
print(constants.Julian_year) #31557600.0
Scipy Optimizers
Optimizers are a set of procedures defined in SciPy that either find the minimum value of a function, or the root
of an equation.
Roots of an Equation
NumPy is capable of finding roots for polynomials and linear equations, but it cannot find roots for nonlinear-
equations, like this one:
x + cos(x)
def eqn(x):
return x + cos(x)
myroot = root(eqn, 0)
print(myroot.x)
O/P:
[-0.73908513]
Finding Minima
'CG'
'BFGS'
'Newton-CG'
'L-BFGS-B'
'TNC'
'COBYLA'
'SLSQP'
return x**2 + x + 2
print(mymin)
O/P:
x: array([-0.50000001]
Matplotlib
Matplotlib is a low-level graph plotting library in python that serves as a visualization utility.
Matplotlib is mostly written in python, a few segments are written in C, Objective-C and Javascript for Platform
compatibility.
Installation of Matplotlib
If you have Python and PIP already installed on a system, then installation of Matplotlib is very easy.
If this command fails, then use a python distribution that already has Matplotlib installed, like Anaconda, Spyder
etc.
Import Matplotlib
Once Matplotlib is installed, import it in your applications by adding the import module statement:
import matplotlib
print(matplotlib.__version__)
O/P:
3.5.3
Pyplot
Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under the plt alias:
import matplotlib.pyplot as plt
Example1
import numpy as np
plt.plot(xpoints, ypoints)
plt.show()
O/P:
Example2
import numpy as np
plt.plot(xpoints, ypoints)
plt.show()
O/P:
Markers
You can use the keyword argument marker to emphasize each point with a specified marker:
Example
import numpy as np
plt.show()
Result:
With Pyplot, you can use the xlabel() and ylabel() functions to set a label for the x- and y-axis.
Example
import numpy as np
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.plot(x, y)
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.show()
Result:
With Pyplot, you can use the grid() function to add grid lines to the plot.
Example
import numpy as np
x = np.array([80, 85, 90, 95, 100, 105, 110, 115, 120, 125])
y = np.array([240, 250, 260, 270, 280, 290, 300, 310, 320, 330])
plt.xlabel("Average Pulse")
plt.ylabel("Calorie Burnage")
plt.plot(x, y)
plt.grid()
plt.show()
Result:
Display Multiple Plots
With the subplots() function you can draw multiple plots in one figure:
Example
Draw 2 plots:
import numpy as np
#plot 1:
x = np.array([0, 1, 2, 3])
y = np.array([3, 8, 1, 10])
plt.subplot(1, 2, 1)
plt.plot(x,y)
#plot 2:
x = np.array([0, 1, 2, 3])
plt.subplot(1, 2, 2)
plt.plot(x,y)
plt.show()
Result:
With Pyplot, you can use the scatter() function to draw a scatter plot.
The scatter() function plots one dot for each observation. It needs two arrays of the same length, one for the
values of the x-axis, and one for values on the y-axis:
Example
x = np.array([5,7,8,7,2,17,2,9,4,11,12,9,6])
y = np.array([99,86,87,88,111,86,103,87,94,78,77,85,86])
plt.scatter(x, y)
plt.show()
Result:
Creating Bars
With Pyplot, you can use the bar() function to draw bar graphs:
Example
Draw 4 bars:
import numpy as np
y = np.array([3, 8, 1, 10])
plt.bar(x,y)
plt.show()
Result:
Histogram
Example
import numpy as np
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Histogram Example')
plt.show()
PIE CHART
import matplotlib.pyplot as plt
import numpy as np
plt.pie(y)
plt.show()
O/P
Labels
The label parameter must be an array with one label for each wedge
import numpy as np
plt.show()