Python Programming Practicals
Python Programming Practicals
Objectives:
To acquire programming skills in core Python.
To understand the data structures in Python.
To develop the skill on files and modules.
To develop the skill of designing Graphical user Interfaces in Python
To develop the ability to write database application in Python.
Aim:
Algorithm:
for n in range(1,numr):
for i in range(2,n):
if(n%i==0):
break
else:
print(n,end=' ')
Output:
2. Write a Python program to perform Linear Search.
Aim:
Algorithm:
3. Use for loop to iterate each element and compare to the key value
for i in range(0,n):
if(list1[i]==key):
return i
return -1
list1=[1,3,5,4,7,8]
key=3
n=len(list1)
res=linear_search(list1,n,key)
if(res==-1):
else:
Output:
3. Write a Python program to multiply using nested loops.
Aim:
Algorithm:
4. Use nested for loops to iterate through each row and each column
Program:
X=[[12,7,3],
[4,5,6],
[7,8,9]]
Y=[[5,8,1,2],
[6,7,3,0],
[4,5,9,1]]
result=[[0,0,0,0],
[0,0,0,0],
[0,0,0,0]]
for i in range(len(X)):
for j in range(len(Y[0])):
for k in range(len(Y)):
result[i][j]+=X[i][k]*Y[k][j]
for r in result:
print(r)
Output:
4. A) Write a Python program to make simple calculator.
Aim:
Algorithm:
return x+y
def subtract(x,y):
return x-y
def multiply(x,y):
return x*y
def divide(x,y):
return x/y
print("Select Operation:")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divivde")
while True:
choice=input("Enter choice(1/2/3/4):")
if choice in('1','2','3','4'):
if choice == '1':
print(num1,"+",num2,"=",add(num1,num2))
print(num1,"-",num2,"=",subtract(num1,num2))
print(num1,"*",num2,"=",multiply(num1,num2))
elif choice == '4':
print(num1,"/",num2,"=",divide(num1,num2))
next_calculation=input("Let's do next
calculation?(Yes/No):")
if next_calculation=="no":
break
else:
print("Invalid Input")
Output:
4. B) Write a program to add numbers and multiply using lambda()?
(Override the default by passing new values as the arguments).
Aim:
Algorithm:
print(add(12,14,16))
print(add(75,126))
print(add(222))
print(add())
print("Multiplication Values")
print(multi(2,4,5))
print(multi(100,22))
print(multi(9))
print(multi())
Output:
4. C) Write Python lambda filter expression checks whether a number is
divisible by two or not.
Aim:
Algorithm:
3. Use the built-in filter function to filter the sequence of list items
print(number)
even_num=list(filter(lambda X:X%2==0,number))
print(even_num)
odd_num=list(filter(lambda X:X%2!=0,number))
print(odd_num)
Output:
4. D) Write a Python program for implementation of mergesort.
Aim:
Algorithm:
5. Merge temp arrays back into arr[l…r] and copy the remaining
elements of L[ ] n R[ ]
6. l is the left side index and r is the right side index of the subarray
of arr to be sorted.
n1 = m-1+1
n2 = r-m
L = [0]*(n1)
R = [0]*(n2)
for i in range(0,n1):
L[i] = arr[1+i]
for j in range(0,n2):
R[j] = arr[m+1+j]
i=0
j=0
k=1
arr[k] = L[i]
i += 1
else:
arr[k] = R[j]
j += 1
k += 1
while i<n1:
arr[k] = L[i]
i += 1
k += 1
while j<n2:
arr[k]=R[j]
j += 1
k += 1
def mergeSort(arr,l,r):
if l<r:
m = l+(r-l)//2
mergeSort(arr,l,m)
mergeSort(arr,m+1,r)
merge(arr,l,m,r)
arr = [12,11,13,5,6,7]
n = len(arr)
for i in range(n):
mergeSort(arr,0,n-1)
for i in range(n):
Aim:
Algorithm:
3. Create a list and perform the Add, Remove, Reverse and Slice
operations
5. ‘if’ condition is used, and if ‘while’ becomes true then print, else
it comes out of the loop
print("List=",List)
if(choice==1):
List.append(val_to_apd)
elif(choice==2):
List.insert(pos,val)
else:
List.extend(ext)
def Slice(List):
print("List=",List)
sli=List[3:8]
print(sli)
sli=List[5: ]
print(sli)
sli=List[ : ]
print(sli)
sli=List[ :-6]
print(sli)
sli=List[-6:-1]
print(sli)
def Reverse(List):
rev=List[::-1]
def Remove(List):
print("List:",List)
if(choice==1):
List.remove(rem)
elif(choice==2):
List.pop(p)
else:
print("AFTER DELETION")
del List[ : ]
print(List)
while True:
x=['P','Y','T','H','O','N','C','L','A','S','S']
print("\n*********OPERATIONS*******")
if(ch==1):
Add(x)
elif(ch==2):
Slice(x)
elif(ch==3):
Reverse(x)
else:
Remove(x)
if cont=="yes":
continue
else:
break
Output:
6. Create Tuple and perform the following methods.
Aim:
Algorithm:
print(thistuple)
thistuple=("apple","banana","cherry","apple","cherry")
print(thistuple)
thistuple=("apple","ball","cat")
print(thistuple[1])
thistuple=("a","b","c")
print(thistuple[-1])
thistuple=("apple","banana","cherry","orange","kiwi","melon","ma
ngo")
print(thistuple[2:5])
fruits=("apple","banana","cherry")
(green,yellow,red)=fruits
print(green)
print(yellow)
print(red)
tuple1=('p','y','t','h','o','n')
tuple2=(1,2,3,4,5)
tuple3=tuple1+tuple2
print(tuple3)
name=("Ashok","Bala","Charles")
mytuple=name*2
print(mytuple)
tuple1=(20,100,10,5,30)
tuple2=(30,20,100,150,0)
if(tuple1!=tuple2):
else:
print("Same")
Output:
7. Create a dictionary and apply the following methods.
4. Adding elements
Aim:
Algorithm:
print(Dict1)
Dict2={'Name':'raja',"Marks":[78,56,83,54]}
print(Dict2)
Dict={}
print("Empty Dictionary:")
print(Dict)
Dict=dict({1:'python',2:'java',3:'c++'})
print(Dict)
Dict=dict([(1,'python'),(2,'java'),(3,'c++')])
print(Dict)
Dict[4]='c'
Dict[5]='c#'
Dict[6]='SQL'
print(Dict)
Dict[2]='JSON'
print(Dict)
Dict={5:'welcome',6:'to',7:'python','A':{1:'py',2:'java',3:'c'},
'B':{1:'CPP',2:'CSS'}}
print("Initial Dictionary:")
print(Dict)
del Dict[6]
print(Dict)
del Dict['A'][2]
print(Dict)
Output:
8. A) Using a numpy module create an array and check the following:
1. Type of array
2. Dimension of array
3. Shape of array
4. Size of array
Aim:
Algorithm:
1. Open Python IDLE & start the program, then import numpy
module
arr=np.array([[1,2,3],
[4,2,5],
[6,7,8]])
print("Array is of Type:",type(arr))
print("No.of Dimensions:",arr.ndim)
print("Shape of array:",arr.shape)
print("Size of array:",arr.size)
Output:
Aim:
Algorithm:
1. Open Python IDLE & start the program, then import numpy
module
3. Create a 3*4 array with all zeros and array with random values
a=np.array([[1,2,4],[5,8,7]],dtype='float')
b=np.array((1,3,2))
c=np.zeros((3,4))
e=np.random.random((2,2))
f=np.arange(0,30,5)
g=np.linspace(0,5,10)
arr=np.array([[1,2,3,4],
[5,2,4,2],
[1,2,0,1]])
newarr=arr.reshape(2,2,3)
print("Reshaped array:\n",newarr)
arr=np.array([[1,2,3],[4,5,6]])
flarr=arr.flatten()
print("Flattend array:\n",flarr)
Output:
Array Created using passed list:
[[1. 2. 4.]
[5. 8. 7.]]
A random array:
[[0.57209042 0.86276734]
[0.7173612 0.44195396]]
original array:
[[1 2 3 4]
[5 2 4 2]
[1 2 0 1]]
Reshaped array:
[[[1 2 3]
[4 5 2]]
[[4 2 1]
[2 0 1]]]
original array:
[[1 2 3]
[4 5 6]]
Flattend array:
[1 2 3 4 5 6]
9. A) Write a program to count the frequency of characters in a given file.
Aim:
Algorithm:
2. Import OS
count=0
file=open("D:/test.txt")
for l in range(0,len(line)):
count+=1
print("count:",count)
filename,file_extension=os.path.splitext("D:/test.txt");
print("file_extension==",file_extension);
if(file_extension=='.py'):
elif(file_extension=='.txt'):
elif(file_extenxion=='.c'):
Output:
9. B) Write a Python program to compute the number of characters, words
and lines in a file.
Aim:
Algorithm:
char,wc,lc=0,0,0
for line in k:
for k in range(0,len(line)):
char+=1
if(line[k]==' '):
wc+=1
if(line[k]=="\n"):
wc,lc=wc+1,lc+1
Output:
10. A) Write a Python program to sort the DataFrame first by ‘name’ in
descending order, then by ‘score’ in ascending order.
Aim:
Algorithm:
Output:
ORIGINAL ROWS:
name score attempts qualify
a Anbhazhagan 12.5 1 yes
b Deepa 9.0 3 no
c Kavitha 16.5 2 yes
d Jothi NaN 3 no
e Ezhil 9.0 2 no
f Murugan 20.0 3 yes
g Mathew 14.5 1 yes
h Latha NaN 1 no
i Kavin 8.0 2 no
j John 19.0 1 yes
SORT THE DATA FRAME FIRST BY 'name' IN DESCENDING ORDER,then by 'score' in
ascending order.
name score attempts qualify
a Anbhazhagan 12.5 1 yes
b Deepa 9.0 3 no
c Kavitha 16.5 2 yes
d Jothi NaN 3 no
e Ezhil 9.0 2 no
f Murugan 20.0 3 yes
g Mathew 14.5 1 yes
h Latha NaN 1 no
i Kavin 8.0 2 no
j John 19.0 1 yes
10. B) Write a Python program to do the following in data frame in pandas.
Aim:
Algorithm:
6. Get the first or last few rows from a series in pandas using head(),
tail() and take()
import numpy as np
employees=pd.DataFrame({'Empcode':['Emp001','Emp002'],'Name
':['John Dae','William spark'],
'occupation':['chemist','statiscian'],'DateofJoin':['2018-01-
25','2018-01-26'],'Age':[23,24]})
index=['Emp001','Emp002'],
columns=['Name','Occupation','DateOfJoin','Age']
print(employees)
employees.columns=['Empcode','Empname','EmpOccupation','Emp
DOJ','EmpAge']
print(employees)
values=["India","Canada","Australia","Japan","Germany","Fra
me"]
code=["IND","CAN","AUS","JAP","GER","FRA"]
ser1=pd.Series(values,index=code)
print("******Head(1)******")
print(ser1.head(1))
print("\n\n***Head(2)*********")
print(ser1.head(2))
print("\n\n.*****Tail(3)********")
print(ser1.tail(3))
print("\n\n*******take(2,4,5)****")
print(ser1.take([2,4,5]))
ser1=pd.Series(np.linspace(1,10,5))
print(ser1)
ser2=pd.Series(np.random.normal(size=5))
print(ser2)
Output:
***Head(2)*********
IND India
CAN Canada
dtype: object
.*****Tail(3)********
JAP Japan
GER Germany
FRA Frame
dtype: object
*******take(2,4,5)****
AUS Australia
GER Germany
FRA Frame
dtype: object
_______after numpy function__
0 1.00
1 3.25
2 5.50
3 7.75
4 10.00
dtype: float64
0 -1.502528
1 1.283191
2 -1.596891
3 0.394048
4 -0.588996
dtype: float64
Aim:
Algorithm:
import sys
try:
s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
port=80
try:
host_ip=socket.gethostbyname('www.google.com')
except socket.gaierror:
sys.exit()
s.connect((host_ip,port))
Aim:
Algorithm:
8. Data pkg more than 1024 bytes will not accepted if not break the
statement
Server:
import socket
def server_program():
host=socket.gethostname()
port=4444
server_socket=socket.socket()
server_socket.bind((host,port))
server_socket.listen(2)
con,address=server_socket.accept()
print("Connection from:"+str(address))
while True:
data=conn.recv(1024).decode()
if not data:
break
data=input('->')
conn.send(data.encode())
conn.close()
if'__name__'=='__main__':
server_program()
Client:
import socket
def client_program():
host=socket.gethostname()
port=4444
client_socket=socket.socket()
client_socket.connect((host, port))
message=input("->")
while message.lower().strip()!='bye':
client_socket.send(message.encode())
data=client_socket.recv(1024).decode()
message=input("->")
client_socket.close()
if __name__=='__main__':
client_program()
Output:
12. Write a Python program to play colour game using tkinter.
Aim:
Algorithm:
8. Change the colour to type, by changing the text and the colour to
a random colour value
9. In countdown(), decrease the timer, and update the time left label
10. In driver code, give exact root code, and call functions
import random
colours=['Red','Blue','Green','Pink','Black','Yellow','Orange','
White','Purple','Brown']
score=0
timeleft=100
def startGame(event):
if(timeleft==100):
countdown()
nextColour()
def nextColour():
global score
global timeleft
if timeleft>0:
e.focus_set()
if e.get().lower()==colours[1].lower():
score+=1
e.delete(0,tkinter.END)
random.shuffle(colours)
label.config(fg=str(colours[1]),text=str(colours[0]))
scoreLabel.config(text="score:"+str(score))
def countdown():
global timeleft
if timeleft>0:
timeleft-=1
timeLabel.config(text="Timeleft:"+str(timeleft))
timeLabel.after(1000,countdown)
root=tkinter.Tk()
root.title("COLORGAME")
root.geometry("375x200")
instructions.pack()
scoreLabel.pack()
timeLabel=tkinter.Label(root,text="Timeleft:"+str(timeleft),font
=('Helvetica',12))
timeLabel.pack()
label=tkinter.Label(root,font=('Helvetica',60))
label.pack()
e=tkinter.Entry(root)
root.bind('<Return>',startGame)
e.pack()
e.focus_set()
root.mainloop()
Output:
13. Write a Python program to handle multiple exceptions with except
statement.
Aim:
Algorithm:
if a < 4:
b = a/(a-3)
print("Value of b = ", b)
def fun2(a):
try:
fun1(3)
fun1(5)
a = [1, 2, 3]
fun2(a)
except ZeroDivisionError:
except NameError:
except IndexError:
finally:
Aim:
Algorithm:
n1=0
n2=1
print(n1)
print(n2)
for x in range(0,n):
n3=n1+n2
if(n3>=n):
break;
else:
print(n3,end='\n')
n1=n2
n2=n3
import fibonacci
n=int(input("ENTER RANGE:"))
if(n<0):
else:
print("*********FIBBONACCI SERIRES********")
fibonacci.fibonacci(n)
Output:
ENTER RANGE:30
*******************FIBONACCI
SERIES***********************
13
21
15. Write a program to create a table by connecting SQL database interface
with sqlite. Perform queries to insert record and display the data.
Aim:
Algorithm:
4. Create a table
conn=sqlite3.connect('stu_dbase.db')
cursor=conn.cursor()
cursor.execute(table)
print(row)
conn.commit()
conn.close()
Output:
('Raju','7th','A')
('Shyam','8th','B')
('Baburao','9th','C')
16. Write a program to implement the concept of CGI & CGIT
Aim:
To write a Python program to create a form using HTML and CGI & CGIT
module.
Algorithm:
form=cgi.FieldStorage()
your_name=form.getvalue('Your_name')
company_name=form.getvalue('company_name')
print("Content_type:text/html\n")
print("<html>")
print("<head>")
print("</head>")
print("<body>")
print("</body>")
print("</html>")
<html>
<body>
<formation="cgil.py" method="get'>
</body>
</html>
Output: