MAR ATHANASIOS COLLEGE FOR ADVANCED STUDIES,
TIRUVALLA (MACFAST)
(Affiliated to Mahatma Gandhi University, Kottayam)
MACFAST
MCA CT 305- PYTHON PROGRAMMING FOR DATA SCIENCE
PRACTICAL RECORD
Name : Jerrin Jacob
Reg. No :
Department of Computer Applications
Mar Athanasios College for Advanced Studies, Tiruvalla (MACFAST)
Kerala, India, Pin-689101
[Link]
[Link]
1
MAR ATHANASIOS COLLEGE FOR ADVANCED STUDIES,
TIRUVALLA (MACFAST)
(Affiliated to Mahatma Gandhi University, Kottayam)
MACFAST
MCA CT 305- PYTHON PROGRAMMING FOR DATA SCIENCE
PRACTICAL RECORD
Name : Jerrin Jacob
Register Number :
Semester :3
Subject : MCA CT 305- Python Programming For Data Science
Certified that this is a bonafide record of the practical work done by
Mr. Jerrin Jacob Reg. No. in the Department of Computer
Applications
During 2021-2023 at Mar Athanasios College of Advanced Studies, Tiruvalla (MACFAST).
Faculty in Charge Head of the Department
Examiners
1……………………………………
2…………………………………….
2
INDEX
[Link] Experiment Page Date
Number
1 Write a program to check whether the given 5 09-01-2023
number is in between a range
2 Python program to compute distance between 7 09-01-2023
two points taking input from the user
(Pythagorean Theorem)
3 Write a python program to accept the number of 9 09-01-2023
days the member is late to return the book and
display the fine or the appropriate message.
4 Program to print a star pyramid pattern 11 09-01-2023
5 Python program to print ‘n’ terms of Fibonacci 13 12-01-2023
series of numbers.
6 Program to find all prime numbers within a given 15 12-01-2023
range
7 Program to print date, time for today and now 17 12-01-2023
8 Create a list and perform the following methods 19 12-01-2023
insert(), remove(), append(), len(), pop(), clear()
9 Program to create a menu with the following 21 22-02-2023
options
[Link] perform addition
2. To perform subtraction
3. To perform multiplication
[Link] perform division
10 Program to find the factorial of a number using 24 22-02-2023
function
11 Python Program to create a vehicle class with 26 22-02-2023
maxspeed, mileage as instant attributes.
12 28 22-02-2023
3
constructor and destructor.
13 Write a program to read the contents of the file 30 08-03-2023
[Link] and calculate the total marks and
percentage obtained by a student.
14 Python program to demonstrate the exception 32 08-03-2023
handling for zero division error.
15 Python program to create and import calculator 34 10-03-2023
module
16 Python program to implement database 36 10-03-2023
connectivity using SQLI
17 Write a program to include multiple exception. 38 10-03-2023
18 Write a function largest which accepts a file 40 10-03-2023
name as a parameter and reports the longest line
in the file.
19 Develop web application with static web pages 42 10-03-2023
using django framework
20 Develop web application with dynamic web 49 13-03-2023
pages using django framework
21 Develop programs for data preprocessing with 54 13-03-2023
pandas and numeric analysis using NumPy
22 Develop programs for implementing plots with 68 13-03-2023
Matplotlib
23 Develop a program based on Linear regression 74 14-03-2023
24 Implementation of at least one classification 76 14-3-2023
algorithm using Scikit-learn
25 Implementation of at least one clustering 79 14-03-2023
algorithm using Scikit-learn
4
PROGRAM NO: 1
Aim: Write a program to check whether the given number is in between a range
Source Code
def test_range(n):
if n in range(3,9):
print( " %s is in the range"%str(n))
else :
print("The number is outside the given range.")
test_range(5)
5
OUTPUT
6
PROGRAM NO:2
Aim: Python program to compute distance between two points taking input from the user
(Pythagorean Theorem)
Source Code
import math;
x1=int(input("Enter x1--->"))
y1=int(input("Enter y1--->"))
x2=int(input("Enter x2--->"))
y2=int(input("Enter y2--->"))
d1 = (x2 - x1) * (x2 - x1);
d2 = (y2 - y1) * (y2 - y1);
res = [Link](d1+d2)
print ("Distance between two points:",res);
7
OUTPUT
8
PROGRAM NO:3
Aim: A library charges a fine for every book returned late. For first five days the fine is 50
paise, for 6 to 10 days the fine is one rupee and above 10 days the fine is five rupees. If you
return the book after 30 days your membership will be cancelled. Write a python program to
accept the number of days the member is late to return the book and display the fine or the
appropriate message.
Source Code
days = int(input("Enter the Number of Days :"))
if (days>0 and days<= 5):
amt = 0.50 * days
print("Fine Amount Pay to Rs :", amt)
elif(days >= 6 and days <= 10):
amt = 1 * days
print("Fine Amount Pay to Rs :", amt)
elif (days > 10):
amt = 5 * days
print("Fine Amount Pay to Rs :", amt)
if (days > 30):
print("Your Membership would be Cancelled..")
else:
print("Invalid")
9
OUTPUT
10
PROGRAM NO:4
Aim: Program to print a star pyramid pattern
Source Code
rows = int(input("Enter number of rows: "))
for i in range(rows):
for j in range(i+1):
print("* ", end="")
print("\n")
11
OUTPUT
12
PROGRAM NO:5
Aim: Python program to print ‘n’ terms of Fibonacci series of numbers.
Source Code
nterms = int(input("How many terms? "))
# first two terms
n1, n2 = 0, 1
count = 0
# check if the number of terms is valid
if nterms <= 0:
print("Please enter a positive integer")
# if there is only one term, return n1
elif nterms == 1:
print("Fibonacci sequence upto",nterms,":")
print(n1)
# generate fibonacci sequence
else:
print("Fibonacci sequence:")
while count < nterms:
print(n1)
nth = n1 + n2
# update values
n1 = n2
n2 = nth
count += 1
13
OUTPUT
14
PROGRAM NO:6
Aim: Program to find all prime numbers within a given range
Source Code
r=int(input("Enter range"))
for a in range(2,r+1):
k=0
for i in range(2,a//2+1):
if(a%i==0):
k=k+1
if(k<=0):
print(a)
15
OUTPUT
16
PROGRAM NO:7
Aim: Program to print date, time for today and now
Source Code
import datetime
a=[Link]()
b=[Link]()
print(a)
print(b)
17
OUTPUT
18
PROGRAM NO:8
Aim: Create a list and perform the following methods
insert(), remove(), append(), len(), pop(), clear()
Source Code
a=[1,3,5,6,7,[3,4,5],"hello"]
print(a)
[Link](3,20)
print(a)
[Link](7)
print(a)
[Link]("hi")
print(a)
len(a)
print(a)
[Link](6)
print(a)
19
OUTPUT
20
PROGRAM NO:9
Aim: Program to create a menu with the following options
[Link] perform addition
2. To perform subtraction
3. To perform multiplication
[Link] perform division
Source Code
def add(a,d):
return a+b
def sub(c,d):
return c-d
def mul(e,f):
return e*f
def div(g,h):
return g/h
print("*******************")
print(" [Link] Perform Addition")
print(" [Link] perform Substraction")
print(" [Link] perform Multiplication")
print(" [Link] perform Division")
print("*******************")
choice=int(input("Enter Your Choice"))
if choice==1:
a=int(input("enter 1st number"))
b=int(input("enter 2nd number"))
21
print(add(a,b))
elif choice==2:
c=int(input("enter 1st number"))
b=int(input("enter 2nd number"))
print(sub(c,d))
elif choice==3:
e=int(input("enter 1st number"))
f=int(input("enter 2nd number"))
print(mul(e,f))
elif choice==4:
g=int(input("enter 1st number"))
h=int(input("enter 2nd number"))
else:
print("wrong choice")
22
OUTPUT
23
PROGRAM NO:10
Aim: Program to find the factorial of a number using function
Source Code
def fact(n):
if n < 0:
return 'Factorial does not exist'
elif n == 0:
return 1
else:
return n * fact(n-1)
num = int(input("enter number"))
print("factorial is")
print(fact(num))
24
OUTPUT
25
PROGRAM NO:11
Aim: Python Program to create a vehicle class with maxspeed, mileage as instant attributes.
Source Code
class Vehicle:
def __init__(self,max_speed,mileage):
self.max_speed=max_speed
[Link]=mileage
a=Vehicle(120,12)
print("max_speed vehicle:",a.max_speed)
print("mileage:",[Link])
26
OUTPUT
27
PROGRAM NO:12
Aim: Python program to demonstrate the concept of constructor and destructor.
Source Code
class Student:
def __init__(self,name):
[Link]=name
print("inside the constructor")
def __del__(self):
print([Link],"Our constructor is destroyed")
def setFullName(self,firstname,lastname):
[Link]=firstname
[Link]=lastname
def printFullName(self):
print([Link]," ", [Link])
StudentName=Student(5)
[Link]("Jerrrin","Jacob")
[Link]()
StudentName.__del__()
28
OUTPUT
29
PROGRAM NO:13
Aim: Write a program to read the contents of the file [Link] and calculate the total marks
and percentage obtained by a student.
Source Code
f1=open("[Link]","r")
n=int([Link]())
print("total:",n)
for i in range(n):
print("student number:",i+1,":",end="")
marks=([Link]().split())
print(marks)
total=0
for j in range(len(marks)):
total=total+int(marks[j])
per=float(total/500*100)
print("total=",total,"\npercentage=",per)
30
OUTPUT
31
PROGRAM NO:14
Aim: Python program to demonstrate the exception handling for zero division error.
Source Code
try:
num1 = int(input("Enter First Number: "))
num2 = int(input("Enter Second Number: "))
result = num1 / num2
print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e:
print(e)
32
OUTPUT
33
PROGRAM NO:15
Aim: Python program to create and import calculator module
Source Code
[Link]
def sum(a,b):
return a+b
def sub(a,b):
return a-b
def mul(a,b):
return a*b
def div(a,b):
return a/b
def rem(a,b):
return a%b
import Calculator
a=[Link](10,3)
print(f"sum{a}")
s=[Link](10,3)
print(f"sub{s}")
m=[Link](10,3)
print(f"mul{m}")
d=[Link](10,3)
print(f"div{d}")
r=[Link](10,3)
print(f"rem{r}")
34
OUTPUT
35
PROGRAM NO:16
Aim: Python program to implement database connectivity using SQLite
Source Code
import sqlite3
try:
con=[Link]('[Link]')
cursor=[Link]()
print("Database Initialised")
q='select sqlite_version();'
[Link](q)
res=[Link]()
print('sqlite version is {}'.format(res))
[Link]()
except [Link] as e:
print('error Encountered',e)
finally:
if con:
[Link]()
print("sqlite connection closed")
36
OUTPUT
37
PROGRAM NO:17
Aim: Write a program to include multiple exception.
Source Code
string=input("enter something here:")
try:
num=int(input("enter a number here:"))
print(string + num)
except (ValueError, TypeError)as a:
print(a)
print("thank you")
38
OUTPUT
39
PROGRAM NO:18
Aim: Write a function largest which accepts a file name as a parameter and reports the
longest line in the file.
Source Code
max_length = 0
max_len_line = ''
file = open("[Link]")
for line in file:
if(len(line) > max_length):
max_length = len(line)
max_len_line = line
print("The Longest line in the file is")
print(max_len_line)
40
OUTPUT
41
PROGRAM NO:19
Aim: Develop web application with static web pages using django framework
Create a Directory for sore the project
Create The Virtual Environment
Install Django
Create the Project
42
Create An Application
Open The Project in any editor and create a Directory Named STATIC to store the plugins
and images that need to display in the Website
Insert an image in STATIC (copy image->paste into static)
Create another Directory Named Templates and Create Html code
43
Create a Function inside the [Link] file in app component
Give path to STATICFILES_DIRS, STATIC_ROOT, MEDIA_URL,MEDIA_ROOT in
[Link]
Project->[Link]
44
Add the newly created TEMPLATE_DIRS in the [Link]
Import OS in [Link]
45
Give the Url of static and Media in the [Link] inside project
Load the Static files , and insert the image and text inside the html file .
46
Give views and path in [Link] inside the app component
Run The Project
47
OUTPUT
48
PROGRAM NO:20
Aim: Develop web application with dynamic web pages using django framework
Create a folder
Create Virtual Environment and activate it.
Install Django
Create Project and Application
Give views and path in [Link] inside the app component
49
Give url of static and media in [Link] in project component
Create Function in [Link] inside app component
Create a Database in [Link]
HERE BOOK IS THE DB NAME, TITLE & PUBDATE ARE FIELDS
50
Register Database into admin
Add App name into installed apps
Apply Migrate into app component
51
Create A Superuser and give username, email and password
Run the project
52
OUTPUT
53
PROGRAM NO:21
Aim: Develop programs for data Preprocessing with pandas and numeric analysis using
NumPy
1) List-To-Series-Conversion
Source Code
Import pandas as pd
given_list = [2, 4, 5, 6, 9]
series = [Link](given_list)
print(series)
OUTPUT
2)List-to-Series conversion with Custom Indexing
Source Code
Import pandas as pd
given_list = [2, 4, 5, 6, 9]
series = [Link](given_list, index = [1, 3, 5, 7, 9])
print(series)
54
OUTPUT
3)Data Series Generation
Source Code
import pandas as pd
date_series = pd.date_range(start = '05-01-2021', end = '05-12-2021')
print(date_series)
4) Implementing a function on each and every element of a series
Source Code
import pandas as pd
series = [Link]([2, 4, 6, 8, 10])
print(series) # pandas series initially
print()
modified_series = [Link](lambda x:x/2) print(modified_series)
55
OUTPUT
5) Dictionary-to-Dataframe Conversion
Source Code
import pandas as pd
dictionary = {'name': ['Vinay', 'Kushal', 'Aman'], 'age' : [22, 25, 24], 'occ' : ['engineer',
'doctor', 'accountant']}
dataframe = [Link](dictionary)
print(dataframe)
OUTPUT
56
6) 2D List-to-Dataframe Conversion
Source Code
import pandas as pd
lists = [[2, 'Vishal', 22], [1, 'Kushal', 25], [1, 'Aman', 24]]
dataframe = [Link](lists, columns = ['id', 'name', 'age'])
print(dataframe)
OUTPUT
57
NUMPY-PROGRAMS
1) Write a NumPy program to test whether none of the elements of a given array is zero
Source Code
import numpy as np
x = [Link]([1, 2, 3, 4])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print([Link](x))
x = [Link]([0, 1, 2, 3])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print([Link](x))
OUTPUT
58
2) Write a NumPy program to test whether any of the elements of a given array is non-
zero.
Source Code
import numpy as np
x = [Link]([1, 0, 0, 0])
print("Original array:")
print(x)
print("Test whether any of the elements of a given array is nonzero:")
print([Link](x))
x = [Link]([0, 0, 0, 0])
print("Original array:")
print(x)
print("Test whether any of the elements of a given array is nonzero:")
print([Link](x))
OUTPUT
59
3) Write a NumPy program to create an element-wise comparison (greater,
greater_equal, less and less_equal) of two given arrays.
Source Code
import numpy as np
x = [Link]([3, 5])
y = [Link]([2, 5])
print("Original numbers:")
print(x)
print(y)
print("Comparison - greater")
print([Link](x, y))
print("Comparison - greater_equal")
print(np.greater_equal(x, y))
print("Comparison - less")
print([Link](x, y))
print("Comparison - less_equal")
print(np.less_equal(x, y))
OUTPUT
60
4) Write a NumPy program to create an array with the values 1, 7, 13, 105 and
determine the size of the memory occupied by the array
Source Code
import numpy as np
X = [Link]([1, 7, 13, 105])
print("Original array:")
print(X)
print("Size of the memory occupied by the said array:")
print("%d bytes" % ([Link] * [Link]))
OUTPUT
61
5) Write a NumPy program to convert a list of numeric value (12.23, 13.32, 100, 36.32)
into a one-dimensional NumPy array.
Source Code
import numpy as np
l = [12.23, 13.32, 100, 36.32]
print("Original List:",l)
a = [Link](l)
print("One-dimensional NumPy array: ",a)
OUTPUT
62
6) Write a NumPy program to create a 3x3 matrix with values ranging from 2 to 10.
Source Code
import numpy as np
x = [Link](2, 11).reshape(3,3)
print(x)
OUTPUT
63
7) Write a NumPy program to create an array with values ranging from 12 to 38.
Source Code
import numpy as np
x = [Link](12, 38)
print(x)
OUTPUT
64
8) Write a NumPy program to reverse an array (first element becomes last)
Source Code
import numpy as np
import numpy as np
x = [Link](12, 38)
print("Original array:")
print(x)
print("Reverse array:")
x = x[::-1]
print(x)
OUTPUT
65
9) Write a NumPy program to create a 2d array with 1 on the border and 0 inside as
shown in the picture below.
Source Code
import numpy as np
x = [Link]((5,5))
print("Original array:")
print(x)
print("1 on the border and 0 inside in the array")
x[1:-1,1:-1] = 0
print(x)
OUTPUT
66
10) Write a NumPy program to append values to the end of an array
Source Code
import numpy as np
x = [10, 20, 30]
print("Original array:")
print(x)
x = [Link](x, [[40, 50, 60], [70, 80, 90]])
print("After append values to the end of the array:")
print(x)
OUTPUT
67
PROGRAM NO:22
Aim: Develop programs for implementing plots with Matplotlib
1) Creating a vertical bar chart
Source Code
import [Link] as plt
x=['one', 'two', 'three', 'four', 'five']
# giving the values against
# each value at x axis
y=[5, 24, 35, 67, 12]
[Link](x, y)
# setting x-label as pen sold
[Link]("pen sold")
# setting y_label as price
[Link]("price")
[Link](" Vertical bar graph")
[Link]()
68
OUTPUT
69
2) Creating a horizontal bar chart
Source Code
import [Link] as plt
y=['one', 'two', 'three', 'four', 'five']
# getting values against each value of y
x=[5,24,35,67,12]
[Link](y, x)
# setting label of y-axis
[Link]("pen sold")
# setting label of x-axis
[Link]("price")
[Link]("Horizontal bar graph")
[Link]()
70
OUTPUT
71
3) Write a Python programming to create a pie chart of the popularity of programming
Languages
Source Code
import [Link] as plt
# Data to plot
languages = 'Java', 'Python', 'PHP', 'JavaScript', 'C#', 'C++'
popuratity = [22.2, 17.6, 8.8, 8, 7.7, 6.7]
colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd",
"#8c564b"]
# explode 1st slice
explode = (0.1, 0, 0, 0,0,0)
# Plot
[Link](popuratity, explode=explode, labels=languages, colors=colors,
autopct='%1.1f%%', shadow=True, startangle=140)
[Link]('equal')
[Link]()
72
OUTPUT
73
PROGRAM NO: 23
Aim: Develop a program based on Linear regression
Source Code
import pandas as pd
import numpy as np
from sklearn import linear_model
import [Link] as plt
df = pd.read_csv('[Link]')
df
%matplotlib inline
[Link]('area')
[Link]('price')
[Link]([Link],[Link],color='red',marker='+')
new_df = [Link]('price',axis='columns')
new_df
price = [Link]
price
# Create linear regression object
reg = linear_model.LinearRegression()
[Link](new_df,price)
[Link]([[3300]])
reg.coef_
reg.intercept_
3300*135.78767123 + 180616.43835616432
[Link]([[5000]])
area_df = pd.read_csv("[Link]")
area_df.head(3)
p = [Link](area_df)
p
area_df['prices']=p
area_df
area_df.to_csv("[Link]")
74
OUTPUT
75
PROGRAM NO:24
Aim: Implementation of at least one classification algorithm using Scikit-learn
Source Code
import os
import pandas as pd
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
%matplotlib inline
#changing working directory to desktop
[Link]("C:\\Users\\User\\Desktop")
#Reading input Data
MyData = pd.read_csv("Classification [Link]")
"
#Viewing Data
#MyData
#Loading machine learning library from sklearn
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import train_test_split
#Separating train and test data
independent_variables = ['Customer_Age','Customer_Loan_Amount']
X = MyData[independent_variables] # independent variable
y = MyData['Loan_Status'] # dependent variable
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.40)
print('train:', len(X_train), 'test:', len(X_test))
76
# instantiate a logistic regression model, and fit with X and y
model = LogisticRegression()
model = [Link](X_train, y_train)
# check the accuracy on the training set
[Link](X_train, y_train)
# predict will give the predited result for test set
print([Link](X_test))
# generate evaluation metrics
from sklearn import metrics
print ("Accuracy ON TEST SET :", metrics.accuracy_score(y_test, [Link](X_test)))
print ("Confusion matrix :",metrics.confusion_matrix(y_test, [Link](X_test)))
#ROC CURVE
# Determine the false positive and true positive rates
fpr, tpr, _ = metrics.roc_curve(y_test, model.predict_proba(X_test)[:,1])
#Receiver operating characteristic
# Calculate the AUC
roc_auc = [Link](fpr, tpr)
print ('ROC AUC: %0.2f' % roc_auc)
# Plot of a ROC curve for a specific class
[Link]()
[Link](fpr, tpr, label='ROC curve (area = %0.2f)' % roc_auc)
#[Link]([0, 1], [0, 1], 'k--')
[Link]([0.0, 1.0])
[Link]([0.0, 1.05])
[Link]('False Positive Rate')
[Link]('True Positive Rate')
[Link]('ROC Curve')
[Link](loc="lower right")
[Link]()
print(fpr)
print(tpr)
77
OUTPUT
78
PROGRAM NO:25
Aim: Implementation of at least one clustering algorithm using Scikit-learn
Source Code
import [Link] as plt
import numpy as np
from [Link] import DBSCAN
from sklearn import metrics
#from [Link].samples_generator import make_blobs The line is now redundant in
python
from [Link] import make_blobs
from [Link] import StandardScaler
from sklearn import datasets
# Load data in X
X, y_true = make_blobs(n_samples=300, centers=4,
cluster_std=0.50, random_state=0)
db = DBSCAN(eps=0.3, min_samples=10).fit(X)
core_samples_mask = np.zeros_like(db.labels_, dtype=bool)
core_samples_mask[db.core_sample_indices_] = True
labels = db.labels_
# Number of clusters in labels, ignoring noise if present.
n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)
print(labels)
# Plot result
# Black removed and is used for noise instead.
unique_labels = set(labels)
colors = ['y', 'b', 'g', 'r']
print(colors)
for k, col in zip(unique_labels, colors):
if k == -1:
# Black used for noise.
79
col = 'k'
class_member_mask = (labels == k)
xy = X[class_member_mask & core_samples_mask]
[Link](xy[:, 0], xy[:, 1], 'o', markerfacecolor=col,
markeredgecolor='k',
markersize=6)
xy = X[class_member_mask & ~core_samples_mask]
[Link](xy[:, 0], xy[:, 1], 'o', markerfacecolor=col,
markeredgecolor='k',
markersize=6)
[Link]('number of clusters: %d' % n_clusters_)
[Link]()
80
OUTPUT
81