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 =[Link]()
print([Link]("%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
[Link]("DATA SAI")
#checking if its added or not
print(colleges)
#adding a new college at a positon
[Link](1,"BHARAT")
print(colleges)
#remove a name from colleges
[Link]("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( )
[Link]("code")
print(college)
#know the length using len()
print("length of college is:",len(college))
#to copy the same dictionary use copy()
mycollege= [Link]()
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 = [Link]('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
[Link](1, 4)
print ("Array after insertion : ", end =" ")
for i in (a):
print (i, end =" ")
print()
# array with float type
b = [Link]('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()
[Link](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:
[Link]
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 [Link]. 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:
[Link]
This is python program
welcome to python
[Link]
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 = [Link]()
#type(cont)
for i in range(0, len(cont)):
[Link](cont[i])
# close the file
[Link]()
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 = [Link]()
# print the content of the file
print("Content of Second file :")
print(cont1)
# close all files
[Link]( )
[Link]( )
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 [Link] 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("[Link]", names=names)
X = [Link][:, :-1]
y = [Link][:, -1]
print([Link]())
Xtrain, Xtest, ytrain, ytest = train_test_split(X, y, test_size=0.10)
classifier = KNeighborsClassifier(n_neighbors=5).fit(Xtrain, ytrain)
ypred = [Link](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