0% found this document useful (0 votes)
39 views16 pages

Ds With Python Lab Manual

The document contains multiple Python programs demonstrating various programming concepts, including data types, arithmetic operations, date formatting, list manipulation, tuple usage, dictionary operations, array handling, module usage, file copying, and implementing the k-Nearest Neighbour algorithm for classification. Each section includes source code and corresponding output examples. The programs cover fundamental aspects of Python programming suitable for educational purposes.

Uploaded by

amarvels95
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views16 pages

Ds With Python Lab Manual

The document contains multiple Python programs demonstrating various programming concepts, including data types, arithmetic operations, date formatting, list manipulation, tuple usage, dictionary operations, array handling, module usage, file copying, and implementing the k-Nearest Neighbour algorithm for classification. Each section includes source code and corresponding output examples. The programs cover fundamental aspects of Python programming suitable for educational purposes.

Uploaded by

amarvels95
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 16

1. Write a program to demonstrate different number data types in python.

Source Code:

i=7
c=24+8j
f=701
s='HELLO EVERYONE!!\nThis is john\'s python programming..'
# NOTE: boolean has truth values that are case sensitive Ex: True (T is caps!)
b=True
print("the value of i is:",i,'\n its type is:',type(i))
print("the value of f is:",f,'\n its type is:',type(f))
print("the value of c is:",c,'\n its type is:',type(c))
print("the value of s is:",s,'\n its type is:',type(s))
print("the value of b is:",b,'\n its type is:',type(b))
print('NOTE: boolean has truth values that are case sensitive Ex: True (T is caps!)')

Output
the value of i is: 7
its type is: <class 'int'>
the value of f is: 701
its type is: <class 'int'>
the value of c is: (24+8j)
its type is: <class 'complex'>
the value of s is: HELLO EVERYONE!!
This is john's python programming..
its type is: <class 'str'>
the value of b is: True
its type is: <class 'bool'>
NOTE: boolean has truth values that are case sensitive Ex: True (T is caps!)
2. Write a program to perform different arithematic operations on numbers
in python.

Source code:

a=10; b=3
print("addition of a:",a,"&b:",b,"is:",a+b)
print("substraction of a:",a,"&b:",b,"is:",a-b)
print("multiplication of a:",a,"&b:",b,"is:",a*b)
print("division of a:",a,"&b:",b,"is:",a/b)
print("floor divison of a:",a,"&b:",b,"is:",a//b)
print("moduli of a:",a,"&b:",b,"is:",a%b)
print("exponent of a:",a,"&b:",b,"is:",a**b)

Output:

addition of a: 10 &b: 3 is: 13


substraction of a: 10 &b: 3 is: 7
multiplication of a: 10 &b: 3 is: 30
division of a: 10 &b: 3 is: 3.3333333333333335
floor divison of a: 10 &b: 3 is: 3
moduli of a: 10 &b: 3 is: 1
exponent of a: 10 &b: 3 is: 1000
3. Write a python script to print the current date in following format Thu Jul 28
12:40:47 2022

Source Code:

import time
import datetime
x =datetime.datetime.now()
print(x.strftime("%c"))

Output:

Thu Jul 28 12:40:47 2022

4. Write a python program to create, append and remove lists in python.


SOURCE CODE:
colleges = ["SPIRTS", "SSCITM", "GITAMS"]
print(colleges)
# appending new college in collges list
colleges.append("DATA SAI")
#checking if its added or not
print(colleges)
#adding a new college at a positon
colleges.insert(1,"BHARAT")
print(colleges)
#remove a name from colleges
colleges.remove("BHARAT")
print(colleges)
#remove a name with an index value
del colleges[1]
# NOTE: index starts from 0 so 2nd value in list will be removed
print(colleges)
OUTPUT
['SPIRTS', 'SSCITM', 'GITAMS']
['SPIRTS', 'SSCITM', 'GITAMS', 'DATA SAI']
['SPIRTS', 'BHARAT', 'SSCITM', 'GITAMS', 'DATA SAI']
['SPIRTS', 'SSCITM', 'GITAMS', 'DATA SAI']
['SPIRTS', 'GITAMS', 'DATA SAI']

5. Write a program to demonstrate working with tuples in python.


SOURCE CODE

# creating tuples with college names..


colleges = ("SPIRTS","SSCITM","GITAMS", "DATA SAI")
print("the lists in colleges tuple is",colleges)
print("we can\'t add or remove new elements in a tuple")
print("length of the tuple colleges is:",len(colleges))
# checking whether 'SPIRTS' is present in the tuple or not
if "SPIRTS" in colleges:
print("Yes, 'SPIRTS' is in the colleges tuple")

OUTPUT
the lists in colleges tuple is ('SPIRTS', 'SSCITM', 'GITAMS', 'DATA SAI')
we can't add or remove new elements in a tuple
length of the tuple colleges is: 4
Yes, 'SPIRTS' is in the colleges tuple
6. Write a program to demonstrate working with dictionaries in python.
SOURCE CODE:
# creating a dictionary
college = {
"name": "SPIRTS",
"code": "SHRD",
"id": "1991"
}
print(college)
#adding items to dictionary
college["location"] = "DATTA PURI"
print(college)
#changing values of a key
college["location"] = "RIMS ROAD"
print(college)
# to remove items use pop( )
college.pop("code")
print(college)
#know the length using len()
print("length of college is:",len(college))
#to copy the same dictionary use copy()
mycollege= college.copy()
print(mycollege)
OUTPUT

{'name': 'SPIRTS', 'code': 'SHRD', 'id': '1991'}

{'name': 'SPIRTS', 'code': 'SHRD', 'id': '1991', 'location': 'DATTA PURI'}

{'name': 'SPIRTS', 'code': 'SHRD', 'id': '1991', 'location': 'RIMS ROAD'}

{'name': 'SPIRTS', 'id': '1991', 'location': 'RIMS ROAD'}

length of college is: 3

{'name': 'SPIRTS', 'id': '1991', 'location': 'RIMS ROAD'}

7. Write a program to demonstrate working with arrays in python.

Source Code:

# Python program to demonstrate


# Adding Elements to a Array
# importing "array" for array creations

import array as arr


# array with int type
a = arr.array('i', [1, 2, 3])
print ("Array before insertion : ", end =" ")
for i in range (0, 3):
print (a[i], end =" ")
print()
# inserting array using
# insert() function
a.insert(1, 4)
print ("Array after insertion : ", end =" ")
for i in (a):
print (i, end =" ")
print()
# array with float type
b = arr.array('d', [2.5, 3.2, 3.3])
print ("Array before insertion : ", end =" ")
for i in range (0, 3):
print (b[i], end =" ")
print()
# adding an element using append()
b.append(4.4)
print ("Array after insertion : ", end =" ")
for i in (b):
print (i, end =" ")
print()

OUTPUT

Array before insertion : 1 2 3


Array after insertion : 1 4 2 3
Array before insertion : 2.5 3.2 3.3
Array after insertion : 2.5 3.2 3.3 4.4
8. Write a python program to define a module and import a specific function
in that module to another program.

Source code:

fibonacci.py

def fibonacci(n):
n1=0;
n2=1;
print(n1)
print(n2)
for x in range(0,n):
n3=n1+n2
if(n3>=n):
break;
print(n3,end = ' ')
n1=n2
n2=n3

using_fibonacci.py

Note: we will be using previous program as a library or package It is mandatory to


write both the programs are separately

from fibonacci import fibonacci


n=int(input("Enter the range"))
if(n<0):
print("enter correct range!!")
else:
print("-------------------------------FIBONACCI SERIES ------------------------- \n")
fibonacci (n)
Output:

Enter the range:10


0
1
1
2
3
5
8
13
21
34

9. Write a script named copyfile.py. This script should prompt the user for the
names of two text files. The contents of the first file should be input and written to
the second file.

Source Code:

file1.txt

This is python program


welcome to python

week16.py

file1=input("Enter First Filename : ")


file2=input("Enter Second Filename : ")
# open file in read mode
fn1 = open(file1, 'r')

# open other file in write mode


fn2 = open(file2, 'w')

# read the content of the file line by line


cont = fn1.readlines()
#type(cont)
for i in range(0, len(cont)):
fn2.write(cont[i])

# close the file


fn2.close()
print("Content of first file copied to second file ")

# open file in read mode


fn2 = open(file2, 'r')

# read the content of the file


cont1 = fn2.read()

# print the content of the file


print("Content of Second file :")
print(cont1)

# close all files


fn1.close( )
fn2.close( )

10. Write a program to implement k-Nearest Neighbour algorithm to classify the iris
data set. Print both correct and wrong predictions. Java/Python ML library classes.
Python Program to Implement and Demonstrate KNN Algorithm

import numpy as np

import pandas as pd

from sklearn.neighbors import KNeighborsClassifier

from sklearn.model_selection import train_test_split

from sklearn import metrics

names = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class']

# Read dataset to pandas dataframe

dataset = pd.read_csv("9-dataset.csv", names=names)

X = dataset.iloc[:, :-1]

y = dataset.iloc[:, -1]

print(X.head())

Xtrain, Xtest, ytrain, ytest = train_test_split(X, y, test_size=0.10)


classifier = KNeighborsClassifier(n_neighbors=5).fit(Xtrain, ytrain)

ypred = classifier.predict(Xtest)

i=0

print ("\n-------------------------------------------------------------------------")

print ('%-25s %-25s %-25s' % ('Original Label', 'Predicted Label', 'Correct/Wrong'))

print ("-------------------------------------------------------------------------")

for label in ytest:

print ('%-25s %-25s' % (label, ypred[i]), end="")

if (label == ypred[i]):

print (' %-25s' % ('Correct'))

else:

print (' %-25s' % ('Wrong'))

i=i+1

print ("-------------------------------------------------------------------------")

print("\nConfusion Matrix:\n",metrics.confusion_matrix(ytest, ypred))

print ("-------------------------------------------------------------------------")

print("\nClassification Report:\n",metrics.classification_report(ytest, ypred))

print ("-------------------------------------------------------------------------")
print('Accuracy of the classifer is %0.2f' % metrics.accuracy_score(ytest,ypred))

print ("-------------------------------------------------------------------------")

Output
sepal-length sepal-width petal-length petal-width

0 5.1 3.5 1.4 0.2

1 4.9 3.0 1.4 0.2

2 4.7 3.2 1.3 0.2

3 4.6 3.1 1.5 0.2

4 5.0 3.6 1.4 0.2

-------------------------------------------------------------------------

Original Label Predicted Label Correct/Wrong

-------------------------------------------------------------------------

Iris-versicolor Iris-versicolor Correct

Iris-virginica Iris-versicolor Wrong

Iris-virginica Iris-virginica Correct

Iris-versicolor Iris-versicolor Correct

Iris-setosa Iris-setosa Correct

Iris-versicolor Iris-versicolor Correct

Iris-setosa Iris-setosa Correct

Iris-setosa Iris-setosa Correct

Iris-virginica Iris-virginica Correct


Iris-virginica Iris-versicolor Wrong

Iris-virginica Iris-virginica Correct

Iris-setosa Iris-setosa Correct

Iris-virginica Iris-virginica Correct

Iris-virginica Iris-virginica Correct

Iris-versicolor Iris-versicolor Correct

-------------------------------------------------------------------------

Confusion Matrix:

[[4 0 0]

[0 4 0]

[0 2 5]]

-------------------------------------------------------------------------

Classification Report:

precision recall f1-score support

Iris-setosa 1.00 1.00 1.00 4

Iris-versicolor 0.67 1.00 0.80 4

Iris-virginica 1.00 0.71 0.83 7


avg / total 0.91 0.87 0.87 15

-------------------------------------------------------------------------

Accuracy of the classifer is 0.87

You might also like