CSA Lab 2

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

Computer System Algorithm (MCS-205) SSUET/QR/114

LAB # 02

Python Modules
OBJECTIVE:
To import python modules and use them in program structure

THEORY

PYTHON MODULE:
A module is a Python object with arbitrarily named attributes that you can bind and reference. Simply, a module is a file
consisting of Python code. A module can define functions, classes and variables. A module can also include runnable
code.

NUMPY LIBRARY:
NumPy is the fundamental package for scientific computing in Python. It is a Python library that provides a
multidimensional array object, various derived objects (such as masked arrays and matrices), and an assortment of
routines for fast operations on arrays, including mathematical, logical, shape manipulation, sorting, selecting, I/O,
discrete Fourier transforms, basic linear algebra, basic statistical operations, random simulation and much more.
NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually numbers), all of
the same type, indexed by a tuple of non-negative integers. In NumPy dimensions are called axes.
You can easily Install it using this command:

The important attributes of an array object are:

function Description
ndim helps find the number of dimensions of a NumPy array.
shape returns the dimension of the array. It is a tuple of integers that indicates the size of
your NumPy array.
size calculates the total number of elements present in the NumPy array.
dtype helps to check what type of elements are stored in the NumPy array.
itemsize helps to find the length of each element of NumPy array in bytes.
data buffer object that points to the start of the NumPy array. However, this attribute
isn’t used much because we usually access the elements in the array using indices.

MATPLOTLIB LIBRARY:
Matplotlib is a low level graph plotting library in python that serves as a visualization utility. Matplotlib is open source
and we can use it freely.
Matplotlib is mostly written in python, a few segments are written in C, Objective-C and JavaScript for Platform
compatibility.
You can easily Install it using this command:

Lab 02: Python Modules


Name: Tanzeel Ur Rehman 1 Roll no: BMCS22-002
Computer System Algorithm (MCS-205) SSUET/QR/114

Most of the Matplotlib utilities lies under the pyplot submodule, and are usually imported under the plt alias:
import matplotlib.pyplot as plt

Plotting x and y points:


The plot() function is used to draw points (markers) in a diagram. By default, the plot() function draws a line from
point to point. The function takes parameters for specifying points in the diagram. Parameter 1 is an array containing
the points on the x-axis. Parameter 2 is an array containing the points on the y-axis.
Example:
import matplotlib.pyplot as plt
import numpy as np

xpoints = np.array([1, 8])


ypoints = np.array([3, 10])

plt.plot(xpoints, ypoints) plt.show()

The important attributes in Matplotlib library:

function Description
marker to emphasize each point with a specified marker:
fmt You can use also use the shortcut string notation parameter to specify the marker.
marker|line|color
Markersize/ms to set the size of the markers
Markeredgecolor/mec to set the color of the edge of the markers.
Linewidth/lw to change the width of the line.
Linestyle/ls to change the style of the plotted line
xlabel()/ylabel()/ functions to set a label for the x- and y-axis
title() function to set a title for the plot.
grid() function to add grid lines to the plot.
subplots() function you can draw multiple plots in one figure
scatter() function plots one dot for each observation.

EXERCISE:
A. Create a file named lab1.py. Write the following code in the file. Execute it and show the output. (You can use
the Snipping Tool to take a snapshot of your output window).
1. Code:
import matplotlib.pyplot as plt
import numpy as np
plt.subplot(2,1,1)
plt.plot([1,4])
plt.subplot(2,1,2)
plt.plot([2,2]) plt.show()

Output:
Lab 02: Python Modules
Name: Tanzeel Ur Rehman 2 Roll no: BMCS22S-002
Computer System Algorithm (MCS-205) SSUET/QR/114

2. Code:
import numpy as np x =
np.array([1, 2, 3, 4, 5, 6])
print("Original array: ",x)
print("Maximum Values: ",np.argmax(x)) print("Minimum Values:
",np.argmin(x))
Output:

B. Point out the errors, if any, in the following Python programs. (also write the correct program in code box)
1. Code:
import numpy as np
x = np.arrange(2, 11),reshape(3:3)
print(a)
Output:

Corrected code:
import numpy as np
x = np.arange(15).reshape(3, 5)
print(x)

2. Code:
import numpy as np

Name: Tanzeel Ur Rehman 3 Roll no: BMCS22S-002


Computer System Algorithm (MCS-205) SSUET/QR/114

import matplotlib.pyplot as plt


plt.plot[[1,2,1,2]]
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.grid() plt.show()
Output:

Corrected code:
import numpy as np
import matplotlib.pyplot as plt
plt.plot(1,2,1,2)
plt.xlabel('x-axis')
plt.ylabel('y-axis')
plt.grid()
plt.show()

C. Create a null vector of size 13 and update n value to n (n=your roll no).
Source Code:
import numpy as np
x = np.zeros(13)
print(x)
print("Update ten value to 11")
x[10] = 10
print(x)
Output:

D. Write a Python program to draw a line plot comparing 3 subject marks of Mathematics, Science and English.
Use marks of 10 students.

Expected output:
Lab 02: Python Modules
Name: Tanzeel Ur Rehman 4 Roll no: BMCS22S-002
Computer System Algorithm (MCS-205) SSUET/QR/114

Source Code:
# ABDUL SAMAD
import matplotlib.pyplot as plt
math_marks = [88, 92, 80, 89, 100, 80, 60, 100, 80, 34]
science_marks = [35, 79, 79, 48, 100, 88, 32, 45, 20, 30]
marks_range = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
english_marks = [33, 30, 70, 78, 100, 80, 27, 49, 17, 22]
plt.plot(marks_range, math_marks, label='Math marks', color='r')
plt.plot(marks_range, science_marks, label='Science marks', color='g')
plt.plot(marks_range, english_marks, label='English marks', color='b')
plt.title('Line Plot')
plt.xlabel('Marks Range')
plt.ylabel('Marks Scored')
plt.legend()
plt.show()
Output:

Name: Tanzeel Ur Rehman 5 Roll no: BMCS22S-002

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy