You are on page 1of 67

Python Programming Lab

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.

1. Write a Python program to find first n prime numbers.

Aim:

To write a Python program to find the first n prime numbers.

Algorithm:

1. Open Python IDLE & start the program

2. Get a value as an input from the user

3. Use a for loop to iterate the number from 1 to N

4. It checks by using (n % i == 0) to find the prime numbers. ‘If’


condition is satisfy then print it

5. Display the result.


Program:
numr=int(input("Enter range:"))

print("Prime Numbers:",end=' ')

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:

To write a Python program to perform Linear Search.

Algorithm:

1. Open Python IDLE & start the program

2. Create a function and pass the arguments

3. Use for loop to iterate each element and compare to the key value

4. If element is found, then return the index position of the key

5. If element is not found, then return -1, which means element is


not present in the list

6. Display the result.


Program:
def linear_search(list1,n,key):

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):

print("Element not found")

else:

print("Element found at index:",res)

Output:
3. Write a Python program to multiply using nested loops.

Aim:

To write the Python program to multiply matrices using nested loops.

Algorithm:

1. Open Python IDLE & start the program

2. Create 3*3 and 3*4 matrices

3. Assign 3*4 matrices for result

4. Use nested for loops to iterate through each row and each column

5. Identify the length of the variables

6. Accumulate sum of products in the result

7. Display the result.

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:

To write a Python program to make a simple calculator.

Algorithm:

1. Open Python IDLE & start the program

2. User to choose an operation. Options 1,2,3 and 4 are valid.


Perform the following operations such as 1. Add, 2. Subtract, 3.
Multiply and 4. Divide

3. If any other input is given by the user, Invalid input is displayed


and the loop continues until a valid option is selected

4. Get a two input values from the user

5. An if-elif-else is used to execute a particular section

6. User-defined functions add(), subtract(), multiply() and divide()


evaluate respective operations

7. Display the result.


Program:
def add(x,y):

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'):

num1=float(input("Enter First Number:"))

num2=float(input("Enter Second Number:"))

if choice == '1':

print(num1,"+",num2,"=",add(num1,num2))

elif choice == '2':

print(num1,"-",num2,"=",subtract(num1,num2))

elif choice == '3':

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:

To write a Python program to add and multiply numbers using lambda


function.

Algorithm:

1. Open Python IDLE & start the program

2. Add and multiply the numbers by using lambda function.

3. Insert the values to the variables

4. Use overriding method by passing values as arguments

5. Display the result.


Program:
add=lambda x=10,y=20,z=30: x+y+z

print(add(12,14,16))

print(add(75,126))

print(add(222))

print(add())

print("Multiplication Values")

multi=lambda x=10,y=20,z=30: x*y*z

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:

To write a Python program to checks whether a number is divisible by


two or not using filter() function.

Algorithm:

1. Open Python IDLE & start the program

2. Declare a list of numbers from 1 to 15

3. Use the built-in filter function to filter the sequence of list items

4. Lambda filter expression checks whether a number is divisible


by two or not

5. Filter method returns all the true values

6. If the number is not divisible by two then that is odd number

7. Display the result.


Program:
number=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]

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:

To write a Python program for implementation of merge sort.

Algorithm:

1. Open Python IDLE & start the program

2. Merge() function is used for merging two halves

3. Merge two subarrays of arr[] and first subarray is arr[l…m],


second subarray is arr[m+l…r]

4. Create temp arrays and copy data to temp arrays L[ ] and R[ ]

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.

7. Print the result.


Program:
def merge(arr,l,m,r):

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

while i<n1 and j<n2:

if L[i] <= R[j]:

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)

print("Given array is")

for i in range(n):

print("%d" % arr[i],end=" ")

mergeSort(arr,0,n-1)

print("\n\n Sorted array is")

for i in range(n):

print("%d" % arr[i],end=" ")


Output:
5. Write a program to create a list and perform the following:

1. Adding elements to the list

2. Removing elements from list

3. Reversing the list

4. Slicing the list

Aim:

To write a Python program to create a list and perform the Add,


Remove, Reverse, and Slice operations.

Algorithm:

1. Open Python IDLE & start the program

2. Define a function with arguments

3. Create a list and perform the Add, Remove, Reverse and Slice
operations

4. Get an input from the user

5. ‘if’ condition is used, and if ‘while’ becomes true then print, else
it comes out of the loop

6. Display the result.


Program:
def Add(List):

print("THE FUNCTIONS ARE ..\n 1.APPEND \n2.INSERT


\n3.EXTEND")

choice=int(input("ENTER THE CHOICE (1/2/3):"))

print("List=",List)

if(choice==1):

val_to_apd=int(input("ENTER THE VALUE TO APPEND"))

List.append(val_to_apd)

print("THE APPENDED LIST IS :",List)

elif(choice==2):

pos=int(input("ENTER THE POSITION WHERE VALUE TO BE


INSERTED:"))

val=input("ENTER THE VALUES TO BE INSERTED")

List.insert(pos,val)

print("THE INSERTED LIST IS:",List)

else:

ext=list(input("ENTER THE VALUES THAT TO EXTENDED IN THE


LIST:"))

List.extend(ext)

print("THE EXTENDED LIST IS:",List)

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]

print("THE REVERSED LIST IS:",rev)

def Remove(List):

print("THE FUNCTIONS ARE ..\n1.REMOVE \n2.POP \n3.DELETE")

choice=int(input("ENTER THE CHOICE (1/2/3)"))

print("List:",List)

if(choice==1):

rem=input("ENTER THE ELEMENT TO BE REMOVED:")

List.remove(rem)

print("THE REMOVED LIST IS:",List)

elif(choice==2):

p=int(input("ENTER THE POSITION TO BE POPED:"))

List.pop(p)

print("THE POPED LIST IS:",List)

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*******")

print("\n1.ADD \n2.SLICING \n3.REVERSE \n4.REMOVE")

ch=int(input("ENTER THE CHOICE (1/2/3/4)"))

if(ch==1):

Add(x)

elif(ch==2):

Slice(x)

elif(ch==3):

Reverse(x)

else:

Remove(x)

cont=input("DO YOU WANT TO CONTINUE (YES/NO):")

if cont=="yes":

continue

else:

break
Output:
6. Create Tuple and perform the following methods.

1. Create Tuple having duplicate values

2. Access Tuple items with positive and negative indexing

3. Unpacking a Tuple, Join Tuples, Multiply Tuples

4. Use of cmp(), max(), min() methods

Aim:

To write a Python program to create a tuple and perform their methods.

Algorithm:

1. Open Python IDLE & start the program

2. First create tuple with values

3. In that tuple give some duplicate values.

4. Then access the tuple item using index position

5. Give negative index position to the tuple

6. Access item with range of indexes

7. It performs the unpacking a tuple, join tuple and multiply


methods

8. It demonstrate the use of cmp(), max(), min()

9. Display the result.


Program:
thistuple=("apple","banana","cherry")

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):

print("Not the same")

else:

print("Same")

print('maximum element in tuples


1,2:'+str(max(tuple1))+','+str(max(tuple2)))

print('minimum element in tuples


1,2:'+str(min(tuple1))+','+str(min(tuple2)))

Output:
7. Create a dictionary and apply the following methods.

1. Create Dictionary with integer keys and mixed keys

2. Create dictionary using dict() method

3. Create dictionary with each item as a pair

4. Adding elements

5. Updating existing values

Aim:

To write a Python program to create a dictionary and apply their


methods.

Algorithm:

1. Open Python IDLE & start the program

2. Create a dictionary with integer keys and mixed keys

3. To use a Dict() method

4. Adding elements to a dictionary one at a time

5. Update an existing key’s value in a dictionary

6. Display the result.


Program:
Dict1={1:'tamil',2:'English',3:'maths'}

print("\n Dictionary with the use of Integer keys:")

print(Dict1)

Dict2={'Name':'raja',"Marks":[78,56,83,54]}

print("\n Dictionary with the use of mixed keys:")

print(Dict2)

Dict={}

print("Empty Dictionary:")

print(Dict)

Dict=dict({1:'python',2:'java',3:'c++'})

print("\n Dictionary with the use of dict():")

print(Dict)

Dict=dict([(1,'python'),(2,'java'),(3,'c++')])

print("\n Dictionary with each item as a pair:")

print(Dict)

Dict[4]='c'

Dict[5]='c#'

Dict[6]='SQL'

print("\n Dictionary after adding 3 elements:")

print(Dict)

Dict[2]='JSON'

print("\n Updated key value:")

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("\n Deleting a Specific key:")

print(Dict)

del Dict['A'][2]

print("\n Deleting a key from Nested Dictionary:")

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

5. Type of elements of array

Aim:

To write a Python program to create an array using a numpy module.

Algorithm:

1. Open Python IDLE & start the program, then import numpy
module

2. Import numpy module

3. Create an array object

4. Print the type of array, dimensions of array, shape of the array


and type of elements of array.

5. Display the result.


Program:
import numpy as np

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)

print("Array stores element of type:",arr.dtype)

Output:

Array is of Type: <class 'numpy.ndarray'>


No.of Dimensions: 2
Shape of array: (3, 3)
Size of array: 9
Array stores element of type: int64
8. B) Using a numpy module create an array and perform the following:

1. Creating array from the list with type float

2. Creating array from tuple

3. Creating a 3*4 array with all zeros

4. Create an array with random values

5. Create a sequence of integers from 0 to 30 with step of 5

6. Create a sequence of 10 values in range 0 to 5

7. Reshaping 3*4 array to 2*2*3 array

8. Flatten the array

9. Reshaping 3*4 array to 2*2*3 array

Aim:

To write a python program to create an array using a numpy module.

Algorithm:

1. Open Python IDLE & start the program, then import numpy
module

2. Create an array from list and tuple

3. Create a 3*4 array with all zeros and array with random values

4. Create a sequence of integers from 0 to 30 with step of 5

5. Create a sequence of 10 values in range of 0 to 5

6. Reshaping 3*4 array to 2*2*3 array

7. Flatten the array

8. Display the result.


Program:
import numpy as np

a=np.array([[1,2,4],[5,8,7]],dtype='float')

print("Array Created using passed list:\n",a)

b=np.array((1,3,2))

print("\n Array created using passed tuple:\n",b)

c=np.zeros((3,4))

print("\n Arra initialized with all zeros:\n",c)

e=np.random.random((2,2))

print("\n A random array:\n",e)

f=np.arange(0,30,5)

print("\n A sequential array with steps of 5:\n",f)

g=np.linspace(0,5,10)

print("\n A sequential array with 10 values between","0 and


5:\n",g)

arr=np.array([[1,2,3,4],

[5,2,4,2],

[1,2,0,1]])

newarr=arr.reshape(2,2,3)

print("\n original array:\n",arr)

print("Reshaped array:\n",newarr)

arr=np.array([[1,2,3],[4,5,6]])

flarr=arr.flatten()

print("\n original array:\n",arr)

print("Flattend array:\n",flarr)
Output:
Array Created using passed list:
[[1. 2. 4.]
[5. 8. 7.]]

Array created using passed tuple:


[1 3 2]

Arra initialized with all zeros:


[[0. 0. 0. 0.]
[0. 0. 0. 0.]
[0. 0. 0. 0.]]

A random array:
[[0.57209042 0.86276734]
[0.7173612 0.44195396]]

A sequential array with steps of 5:


[ 0 5 10 15 20 25]

A sequential array with 10 values between 0 and 5:


[0. 0.55555556 1.11111111 1.66666667 2.22222222 2.77777778
3.33333333 3.88888889 4.44444444 5. ]

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:

To write a python program to count the frequency of characters in a


given file.

Algorithm:

1. Open Python IDLE & start the program

2. Import OS

3. Assign count=0, file(“D:/file_test.txt”), i.e, required file is open


by open(), inside that path of the file is given

4. Use for loop to iterate till length of the file

5. Use if statement to check the extension of a given file

6. Display the result.


Program:
import os

count=0

file=open("D:/test.txt")

for line in file:

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'):

print("its python program file");

elif(file_extension=='.txt'):

print("its a text file");

elif(file_extenxion=='.c'):

print("its a c program file");

Output:
9. B) Write a Python program to compute the number of characters, words
and lines in a file.

Aim:

To write a Python program to compute the number of characters, words


and lines in a file.

Algorithm:

1. Open Python IDLE & start the program

2. Open a file using open()

3. Use for loop iteration with condition length of the line

4. Use if statement to store respective counts to respective variables

5. Print the number of chars, words, lines in the opened file

6. Display the result.


Program:
k=open('D:/sam.txt','r')

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

print('''The no.of chars is %d\n the no.of words is %d\n The


no.of lines is %d'''%(char,wc,lc))

Output:
10. A) Write a Python program to sort the DataFrame first by ‘name’ in
descending order, then by ‘score’ in ascending order.

Aim:

To write a Python program to sort DataFrame by ‘name’ in descending


order, then by ‘score’ in ascending order.

Algorithm:

1. Open Python IDLE & start the program

2. Import panda and numpy module

3. Create a dictionary which contains list, and create a separate list

4. Use a pd dataframe to assign index to labels

5. Sort index by df.sort_values(by) statement

6. Print the result


Program:
import pandas as pd
import numpy as np
exam_data={'name':['Anbhazhagan','Deepa','Kavitha','Jothi','Ezhi
l','Murugan','Mathew','Latha','Kavin','John'],'score':[12.5,9,16
.5,np.nan,9,20,14.5,np.nan,8,19],'attempts':[1,3,2,3,2,3,1,1,2,1
],'qualify':['yes','no','yes','no','no','yes','yes','no','no','y
es']}
labels=['a','b','c','d','e','f','g','h','i','j']
df=pd.DataFrame(exam_data,index=labels)
print("ORIGINAL ROWS:")
print(df)
df.sort_values(by=['name','score'],ascending=[False,True])
print("SORT THE DATA FRAME FIRST BY 'name' IN DESCENDING
ORDER,then by 'score' in ascending order.")
print(df)

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.

1. Create and print the DataFrame in pandas

2. Set index and columns in pandas DataFrame

3. Rename the DataFrame

4. Get the first and last rows in series

5. Create series numpy

Aim:

To write a program to do certain operations in data frame in


pandas[i.e., To create and print df, set index and column, rename, first and last
rows, create series numpy in pandas dataframe].

Algorithm:

1. Open Python IDLE & start the program

2. Import panda and numpy module

3. Create DataFrame employees using pd.DataFrame

4. Set index and column name in pandas

5. Rename the DataFrame columns name as employee by


employee.columns

6. Get the first or last few rows from a series in pandas using head(),
tail() and take()

7. Create series using numpy by pd.series

8. Display the result


Program:
import pandas as pd

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("*********AFTER INDEXING THE EMPCODE**********")

print(employees)

employees.columns=['Empcode','Empname','EmpOccupation','Emp
DOJ','EmpAge']

print("**********AFTER REMAINING ********")

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("_______after numpy function__")

print(ser1)

ser2=pd.Series(np.random.normal(size=5))

print(ser2)

Output:

*********AFTER INDEXING THE EMPCODE**********


Empcode Name occupation DateofJoin Age
0 Emp001 John Dae chemist 2018-01-25 23
1 Emp002 William spark statiscian 2018-01-26 24
**********AFTER REMAINING ********
Empcode Empname EmpOccupation EmpDOJ EmpAge
0 Emp001 John Dae chemist 2018-01-25 23
1 Emp002 William spark statiscian 2018-01-26 24
******Head(1)******
IND India
dtype: object

***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

11. A) Write a script to connect to Google using socket programming in


Python.

Aim:

To write a script to connect to Google using socket program in Python

Algorithm:

1. Start the program

2. Import socket using socket.socket, and if failed return, socket


creation is failed, in ‘try:’- exception handling

3. Set default port=80, and again try(), give google website to


connect, if it could not resolve the host, throws an error

4. Connect the server using, s.connect((host_ip,port))

5. Stop the process.


Program:
import socket

import sys

try:

s=socket.socket(socket.AF_INET,socket.SOCK_STREAM)

print("SOCKET CREATED SUCCESSFULLY")

except socket.error as err:

print("SOCKET CREATION FAILED WITH ERROR %s"%(err))

port=80

try:

host_ip=socket.gethostbyname('www.google.com')

except socket.gaierror:

print("THERE WAS AN ERROR RESOLVING THE HOST")

sys.exit()

s.connect((host_ip,port))

print("THE SOCKET HAS SUCCESSFULLY CONNECTED TO GOOGLE",host_ip)


Output:
11. B) Write a program to connect server and client in Python.

Aim:

To write a program to connect server and client program.

Algorithm:

1. Start the program

2. Import socket module

3. Define or create a function named server_program

4. To get the hostname use socketgethehostname()

5. Initialize port numer, use blind() to take tupleas argument

6. Configure no of client and server can listen simultaneously

7. Use accept(), accept new connection

8. Data pkg more than 1024 bytes will not accepted if not break the
statement

9. conn.send is used to send data to the client and close the


connection.

10. Similar procedure is followed in client_program but with () to


receive response

11. Stop the process.


Program:

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

print("FROM CONNECTED USER :"+str(data))

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()

print("Recieved from server:"+data)

message=input("->")

client_socket.close()

if __name__=='__main__':

client_program()
Output:
12. Write a Python program to play colour game using tkinter.

Aim:

To write a Python program to play colour game using tkinter.

Algorithm:

1. Open Python IDLE & start the program

2. List a possible colours

3. Initialize timeleft=30 seconds

4. Create a(), named startgame(event) as argument use countdown()


to start timer

5. To run the function to choose next colour use net colour()

6. Create another(0, and create global score and timeleft. If game is


currently played, use p.focus_set() to entry box active

7. If the colour type is equal, to the colour of test, then score is


incremented

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

11. Play the game!


Program:
import tkinter

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=tkinter.Label(root,text="Type in the colour of the


words,and not the word text!",font=('Helvetica',12))

instructions.pack()

scoreLabel=tkinter.Label(root,text="PRESS ENTER TO START


",font=('Helvetica',12))

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:

To write a python program to handle multiple exceptions with one


except statement.

Algorithm:

1. Open Python IDLE & start the program

2. Create or define a functions such as fun1() and fun2()

3. In a fun1(), print the value of b after performing given expression

4. In a fun2(), is to print the 2nd & 4th element. To throw an error,


‘try’ method is used, in that pass value to fun1()

5. Then ‘a’ contains, only three variable, pass ‘a’ to fun2()

6. Name the error that may happen in the program

7. Here, only three arguments are passed to fun2(), but there is a


statement to print 4th element. Here, the error handling works.

8. Kind of error occurred has been printed.


Program:
def fun1(a):

if a < 4:

b = a/(a-3)

print("Value of b = ", b)

def fun2(a):

print ("Second element = %d" %(a[1]))

print ("Fourth element = %d" %(a[4]))

try:

fun1(3)

fun1(5)

a = [1, 2, 3]

fun2(a)

except ZeroDivisionError:

print("ZeroDivisionError Occurred and Handled")

except NameError:

print("NameError Occurred and Handled")

except IndexError:

print ("Index error occurred and handled")

finally:

print('This is always executed')


Output:
14. Write a Python program to define a module to find Fibonacci numbers
and import the module to another program.

Aim:

To write a python program to define a module to find Fibonacci


numbers.

Algorithm:

1. Open Python IDLE & start the program

2. Define a function Fibonacci, and define Fibonacci expression in


the function

3. As this program is a library or package, we need to create an


another program

4. In an another program, import Fibonacci module

5. Get the range value from the user

6. If the range is less than 0, then print the statement “Enter a


Correct range!”

7. Else, call Fibonacci program, which was already done, it can be


called by using fibonacci.fibonacci(n).
Program:
def fibonacci(n):

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):

print("ENTER CORRECT RANGE:")

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:

To write a python program to create table by connecting SQL database


interface with sqlite. Perform queries to insert record and display the data.

Algorithm:

1. Open Python IDLE & start the program

2. Import “sqlite3” and connect database by (student2)

3. Create a cursor object using the cursor() method

4. Create a table

5. Queries to insert record

6. Display the data which are inserted

7. Commit the changes in the database

8. Close the connection and execute.


Program:
import sqlite3

conn=sqlite3.connect('stu_dbase.db')

cursor=conn.cursor()

table="""CREATE TABLE ST(NAME VARCHAR(244),CLASS


VARCHAR(244),SECTION VARCHAR(244));"""

cursor.execute(table)

cursor.execute('''INSERT INTO ST VALUES('Raju','7th','A')''')

cursor.execute('''INSERT INTO ST VALUES('Shyam','8th','B')''')

cursor.execute('''INSERT INTO ST VALUES('Baburao','9th','C')''')

print("DATA INSERTED IN THE TABLE:")

data=cursor.execute('''SELECT * FROM ST''')

for row in data:

print(row)

conn.commit()

conn.close()
Output:

DATA INSERTED IN THE TABLE:

('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:

1. Open Python IDLE & start the program

2. Import CGI and CGIT module

3. Create instance of field storage class which we can use to work,


with the submitted form

4. Get the data from the fields

5. Print required data

6. In a notepad, write a html code to create form

7. Call python program by ‘program_name.py’ in form action

8. Output will be displayed.


Program:
import cgi,cgitb

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("<title>FIRST CGI PROGRAM </title>")

print("</head>")

print("<body>")

print("<h3>Hello,%s is working in %s </h2>" %


(your_name,company_name))

print("</body>")

print("</html>")

<html>

<body>

<h1> WELCOME TO THE CGI PROGRAM </h1> <br>

<formation="cgil.py" method="get'>

Name:<input type="text" name="Your_name"> <br/>

Copmany_name:<input type="text" name="Company_name">

<input type="submit" value="submit"/>

</body>

</html>
Output:

You might also like