Python Record Final
Python Record Final
TIRUVALLA (MACFAST)
(Affiliated to Mahatma Gandhi University, Kottayam)
MACFAST
MCA CT 305- PYTHON PROGRAMMING FOR DATA SCIENCE
PRACTICAL RECORD
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
Examiners
1……………………………………
2…………………………………….
2
INDEX
SL.No Experiment Page Date
Number
3
constructor and destructor.
13 Write a program to read the contents of the file 30 08-03-2023
mark.txt 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.
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 = math.sqrt(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
9
OUTPUT
10
PROGRAM NO:4
Source Code
for i in range(rows):
for j in range(i+1):
print("* ", end="")
print("\n")
11
OUTPUT
12
PROGRAM NO:5
Source Code
13
OUTPUT
14
PROGRAM NO:6
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
Source Code
import datetime
a=datetime.datetime.today()
b=datetime.datetime.now()
print(a)
print(b)
17
OUTPUT
18
PROGRAM NO:8
Source Code
a=[1,3,5,6,7,[3,4,5],"hello"]
print(a)
a.insert(3,20)
print(a)
a.remove(7)
print(a)
a.append("hi")
print(a)
len(a)
print(a)
a.pop(6)
print(a)
19
OUTPUT
20
PROGRAM NO:9
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(" 1.To Perform Addition")
print(" 2.To perform Substraction")
print(" 3.To perform Multiplication")
print(" 4.To perform Division")
print("*******************")
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
Source Code
def fact(n):
if n < 0:
return 'Factorial does not exist'
elif n == 0:
return 1
else:
return n * fact(n-1)
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
self.mileage=mileage
a=Vehicle(120,12)
print("max_speed vehicle:",a.max_speed)
print("mileage:",a.mileage)
26
OUTPUT
27
PROGRAM NO:12
Source Code
class Student:
def __init__(self,name):
self.name=name
print("inside the constructor")
def __del__(self):
print(self.name,"Our constructor is destroyed")
def setFullName(self,firstname,lastname):
self.firstname=firstname
self.lastname=lastname
def printFullName(self):
print(self.firstname," ", self.lastname)
StudentName=Student(5)
StudentName.setFullName("Jerrrin","Jacob")
StudentName.printFullName()
StudentName.__del__()
28
OUTPUT
29
PROGRAM NO:13
Aim: Write a program to read the contents of the file mark.txt and calculate the total marks
and percentage obtained by a student.
Source Code
f1=open("marks.txt","r")
n=int(f1.readline())
print("total:",n)
for i in range(n):
print("student number:",i+1,":",end="")
marks=(f1.readline().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: "))
print(result)
except ValueError as e:
print("Invalid Input Please Input Integer...")
except ZeroDivisionError as e:
print(e)
32
OUTPUT
33
PROGRAM NO:15
Source Code
Calculator.py
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=Calculator.sum(10,3)
print(f"sum{a}")
s=Calculator.sub(10,3)
print(f"sub{s}")
m=Calculator.mul(10,3)
print(f"mul{m}")
d=Calculator.div(10,3)
print(f"div{d}")
r=Calculator.rem(10,3)
print(f"rem{r}")
34
OUTPUT
35
PROGRAM NO:16
Source Code
import sqlite3
try:
con=sqlite3.connect('new.db')
cursor=con.cursor()
print("Database Initialised")
q='select sqlite_version();'
cursor.execute(q)
res=cursor.fetchall()
print('sqlite version is {}'.format(res))
cursor.close()
except sqlite3.Error as e:
print('error Encountered',e)
finally:
if con:
con.close()
print("sqlite connection closed")
36
OUTPUT
37
PROGRAM NO:17
Source Code
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("hai.txt")
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
Install Django
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
43
Create a Function inside the views.py file in app component
44
Add the newly created TEMPLATE_DIRS in the settings.py
Import OS in settings.py
45
Give the Url of static and Media in the urls.py inside project
Load the Static files , and insert the image and text inside the html file .
46
Give views and path in urls.py inside the app component
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
49
Give url of static and media in urls.py in project component
50
Register Database into admin
51
Create A Superuser and give username, email and password
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 = pd.Series(given_list)
print(series)
OUTPUT
Source Code
Import pandas as pd
given_list = [2, 4, 5, 6, 9]
series = pd.Series(given_list, index = [1, 3, 5, 7, 9])
print(series)
54
OUTPUT
Source Code
import pandas as pd
date_series = pd.date_range(start = '05-01-2021', end = '05-12-2021')
print(date_series)
Source Code
import pandas as pd
series = pd.Series([2, 4, 6, 8, 10])
print(series) # pandas series initially
print()
modified_series = series.apply(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 = pd.DataFrame(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 = pd.DataFrame(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 = np.array([1, 2, 3, 4])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(x))
x = np.array([0, 1, 2, 3])
print("Original array:")
print(x)
print("Test if none of the elements of the said array is zero:")
print(np.all(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 = np.array([1, 0, 0, 0])
print("Original array:")
print(x)
print(np.any(x))
x = np.array([0, 0, 0, 0])
print("Original array:")
print(x)
print(np.any(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 = np.array([3, 5])
y = np.array([2, 5])
print("Original numbers:")
print(x)
print(y)
print("Comparison - greater")
print(np.greater(x, y))
print("Comparison - greater_equal")
print(np.greater_equal(x, y))
print("Comparison - less")
print(np.less(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
print("Original array:")
print(X)
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
print("Original List:",l)
a = np.array(l)
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 = np.arange(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 = np.arange(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 = np.arange(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 = np.ones((5,5))
print("Original array:")
print(x)
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
print("Original array:")
print(x)
print(x)
OUTPUT
67
PROGRAM NO:22
Source Code
plt.bar(x, y)
plt.xlabel("pen sold")
plt.ylabel("price")
plt.show()
68
OUTPUT
69
2) Creating a horizontal bar chart
Source Code
x=[5,24,35,67,12]
plt.barh(y, x)
plt.ylabel("pen sold")
plt.xlabel("price")
plt.show()
70
OUTPUT
71
3) Write a Python programming to create a pie chart of the popularity of programming
Languages
Source Code
# Data to plot
"#8c564b"]
# Plot
plt.axis('equal')
plt.show()
72
OUTPUT
73
PROGRAM NO: 23
Source Code
import pandas as pd
import numpy as np
from sklearn import linear_model
import matplotlib.pyplot as plt
df = pd.read_csv('homeprices.csv')
df
%matplotlib inline
plt.xlabel('area')
plt.ylabel('price')
plt.scatter(df.area,df.price,color='red',marker='+')
new_df = df.drop('price',axis='columns')
new_df
price = df.price
price
# Create linear regression object
reg = linear_model.LinearRegression()
reg.fit(new_df,price)
reg.predict([[3300]])
reg.coef_
reg.intercept_
3300*135.78767123 + 180616.43835616432
reg.predict([[5000]])
area_df = pd.read_csv("areas.csv")
area_df.head(3)
p = reg.predict(area_df)
p
area_df['prices']=p
area_df
area_df.to_csv("prediction.csv")
74
OUTPUT
75
PROGRAM NO:24
Source Code
import os
import pandas as pd
import numpy as np
import seaborn as sns
from matplotlib import pyplot as plt
%matplotlib inline
"
#Viewing Data
#MyData
76
# instantiate a logistic regression model, and fit with X and y
model = LogisticRegression()
model = model.fit(X_train, y_train)
#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 = metrics.auc(fpr, tpr)
print ('ROC AUC: %0.2f' % roc_auc)
print(fpr)
print(tpr)
77
OUTPUT
78
PROGRAM NO:25
Source Code
# 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_
print(labels)
# Plot result
79
col = 'k'
class_member_mask = (labels == k)
80
OUTPUT
81