0% found this document useful (0 votes)
244 views67 pages

Lab Manual - Old

Here are the functions to perform bubble sort and insertion sort on a list of numbers entered by the user: def bubble_sort(list1): n = len(list1) for i in range(n): for j in range(0, n-i-1): if list1[j] > list1[j+1] : temp = list1[j] list1[j] = list1[j+1] list1[j+1] = temp return list1 def insertion_sort(list1): for i in range(1,len(list1)): key = list1[i] j = i-1

Uploaded by

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

Lab Manual - Old

Here are the functions to perform bubble sort and insertion sort on a list of numbers entered by the user: def bubble_sort(list1): n = len(list1) for i in range(n): for j in range(0, n-i-1): if list1[j] > list1[j+1] : temp = list1[j] list1[j] = list1[j+1] list1[j+1] = temp return list1 def insertion_sort(list1): for i in range(1,len(list1)): key = list1[i] j = i-1

Uploaded by

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

SRM UNIVERSITY

DEPARTMENT OF INFORMATION TECHNOLOGY

15IT322E – PYTHON PROGRAMMING

TUTORIAL RECORD
B.TECH V SEMESTER

REGISTER NUMBER
NAME
Week Date NameoftheExperiment Mar Sign
0 Python Installation, Environment
Preliminaries - -
1 Lists and Tuples
2 Dictionaries and Strings
3 Classes
4 File Handling
5 Threads
6 Socket Programming
7 CGI scripts
8 GUI application using TKinter
9 Databases

INDEX
Python Installation, Environment
Steps to install python:

Operating System: Windows

1. Download Python3.6.2 or python 2.7 from www.python.org

2. Double click the downloaded python installer and install it

Setting environment path variable

1. Open control panel ->Systems->Advanced System settings->Environment


variables

2. Under System variables ->Edit PATH->Add path of Python.exe file(Eg:


C:\Python27)->ok
Steps to start the program using IDLE

1. Start python IDLE

2. This starts the python shell. You can type in simple commands to see how
they work. Try typing the following:

Print(‘hello’)
3. In order to do more elaborate programs, normally people store all the
commands in a file. To open a file to use in this way, go to File -> New
Window.
4. In this file , type your print command
5. Save it by File->save

While saving use .py as filename extension if you are using python 2.x version
otherwise give just the name.

6. Run your program, by going to Run -> Run Module.


6. Here is what the output will look like.
To run a saved file using windows command prompt

1. start command prompt

2. Type

python filename.py

(prefix the filename with its complete path )


Preliminaries
Ungraded Introductory Experiments

Part I – Operators and Expressions


1 Loss or Profit
Write a program to calculate the loss or profit (i.e., difference on price) in a
book purchase at outlet or online. The program gets the price of the book you
bought at outlet as input. Then it asks for the average price of the book, if
bought online. The program computes the difference between these prices and
displays the output.
Sample Output:

Solution:

price_store = input("Enter average price of the book when bought at an


outlet store : ")
price_online = input("Enter average price of the book when bought
online : ")

difference = int(price_store) - int(price_online)

if(difference < 0):


difference = -1 * difference

print("The difference in prices between online and store bought books are
: ", difference)

2. VAT Calculator
Write a python program for VAT Calculation. The program gets the net
payable amount as input from the user. Then the program asks for VAT
percentage from the user. The program computes the net amount and VAT
amount and displays the result to the user.
Sample Output:

Solution:
amount = int(input("Enter the total amount : "))
vat_percent = int(input("Enter VAT percentage : "))

vat_amount = amount * vat_percent//100


net_amount = amount + vat_amount

print("VAT Amount : ", vat_amount)


print("Net Amount : ", net_amount)

3. Side of a triangle
Write a python program to compute the third side of a triangle when two
sides and an angle are given.

The program gets side1, side2 and angle 1 as input from the user and
computes the side 3, using the above formula.
Hint : import math module. Use functionalities like sqrt, cos from the
module. Cos function expects the parameter to be in radians. Convert the
degress got from user to radians using the function, radians(angle)

Sample Output:

Solution:
import math
side1 = float(input("Enter side 1 : "))

side2 = float(input("Enter side 2 : "))


angle = float(input("Enter angle in degrees : "))

side3 = math.sqrt(side1**2 + side2**2 - 2*side1*side2*math.cos(angle))

print("The third side is : ", side3)

Part II – Flow Controls & Functions

1. Write a program using nested loops to print the below pattern. Get the
number of lines from user.

Solution:

n=int(input())

for i in range(0,n):

for k in range(0,i):

print("\\ \\ ",end="")

for j in range(i*2,(n*2-1)):

print("! ! ", end="")


for k in range(0, i):

print("/ / ", end="")

print("\n")

2. Zellers Algorithm
Write a program to compute Zeller’s algorithm, which is used to tell the
day of the week, provided a date is given.
Ask the user for the month as a number between 1 – 12 where March is 1
and February is 12.
If born in Jan or Feb, enter previous year.

Zeller’s algorithm computation is defined as follows:


Let A, B, C, and D denote integer variables that have the following
values:
A = the month of the year, with March having the value 1, April the value
2,
December the value 10, and January and February being counted as
months 11 and
12 of the preceding year (in which case, subtract 1 from C)
B = the day of the month (1, 2, 3, … , 30, 31)
C = the year of the century (e.g. C = 89 for the year 1989)
D = the century (e.g. D = 19 for the year 1989)
Note: if the month is January or February, then the preceding year is used
for computation. This is because there was a period in history when
March 1st, not January 1st, was the beginning of the year.

Let W, X, Y, Z, R also denote integer variables. Compute their values in


the following
order using integer arithmetic:
W = (13*A - 1) / 5
X=C/4
Y=D/4
Z = W + X + Y + B + C - 2*D
R = the remainder when Z is divided by 7

Hint: Use integer division “//” for division


Now the value of “R” is used to find the day of the week.
If R is zero, then it is a Sunday. If R is one, then it is Monday and so on.
When R = 6, the day is Saturday.

Sample Output:

Solution:

print("Zellers algorithm to return the day of the week for any year")

month = int(input("Month : "))

day = int(input("Day : "))

year = int(input("Year : "))

cent = int(input("Century : "))

month = month - 2

if month == 0:

month = 12

year = year - 1

elif month == -1:

month = 11

year = year - 1

W = (13*month - 1)//5

X = year//4

Y = cent//4

Z = W + X + Y + day + year - 2*cent


days = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday",
"Saturday"]

print("The day is", days[Z%7])

3. Luhn’s algorithm

Write a program to verify valid credit card number. A valid card number passes
a digit-sum test known as the Luhn checksum algorithm. Luhn's algorithm states
that if you sum the digits of the number in a certain way, the total sum must be a
multiple of 10 for a valid number. Systems that accept credit cards perform a
Luhn test before contacting the credit card company for final verification.

The algorithm for summing the digits is the following. Consider each digit of
the credit card to have a zero-based index: the first (starting from right) is at
index 0, and the last is at index 15. Start from the rightmost digit and process
each digit one at a time. For digits at even-numbered indexes (the 14th digit,
12th digit, etc.), simply add that digit to the cumulative sum. For digits at odd-
numbered indexes (the 15th, 13th, etc), double the digit's value, then if that
doubled value is less than 10, add it to the sum. If the doubled number is 10 or
greater, add each of its digits separately into the sum.

The following pseudocode describes the Luhn algorithm to sum the digits:

4408041254369873 is an example credit card number that passes the


Luhn algorithm. The following figure shows the algorithm summing the
latter number in detail. Notice how digits at even indexes are doubled and
potentially split into two digits if they exceed 10 when doubled. For
example, the number 7 at index 8 which is doubled to 14 which split to
make 1+4.

An example checksum using the Luhn algorithm.


CC # 4408 0412 5436 9873

4 4 0 8 0 4 1 2 7 4 3 6 9 8 5 3
Scale *2 *2 *2 *2 *2 *2 *2 *2
--------------------------------------------------------------------
8 4 0 8 0 4 2 2 14 4 6 6 18 8 10 3

Sum = 8 + 4 + 0 + 8 + 0 + 4 + 2 + 2 + 1+4 + 4 + 6 + 6 + 1+8 + 8 + 1+0 + 3


= 70
70 is divisible by 10, therefore this card number is valid.

Write a program where the user can type in a credit card number and
receive a message stating whether the number was valid. The program
should have a function validate_number() that takes the credit card
number as argument and prints the message “Valid Credit Card Number”
or “Invalid Credit Card Number” accordingly. The program should print
an error message and exit if the length of the credit card number is not
equal to 16.

Sample Output:

Solution:

def luhn_checksum(card_number):

def digits_of(n):

return [int(d) for d in str(n)]

digits = digits_of(card_number)

odd_digits = digits[-1::-2]

even_digits = digits[-2::-2]

checksum = 0

checksum += sum(odd_digits)

for d in even_digits:

checksum += sum(digits_of(d*2))

return checksum % 10

def is_luhn_valid(card_number):

return luhn_checksum(card_number) == 0
a=int(input("Enter the credit card no."))

result = is_luhn_valid(a)

if(str(result)):

print("Credit card is valid")

else:

print("Credit card is invalid")


Graded Questions:
1a)Lists
Get a list of numbers from the user, till he types “end”. Write two functions
“bubble_sort” and “insertion_sort”, to sort the function using bubble sort and
insertion sort. Arguments to the function would be user entered list. The
function returns the sorted list according to the algorithm.
Hint – Working of algorithms
Bubble Sort:
 Basic idea is to bubble up the largest(or smallest), then the 2nd largest
and the the 3rd and so on to the end of the list.
 Each bubble up takes a full sweep through the list
 Do the sorting in place. Do not create a new list.
Insertion Sort:
 Take element by element and insert it at the right position
 Do the sorting in place. Do not create a new list.

1b) Tuples
Get a list of non-empty tuples from the user. You can use any end of sequence
representation for tuples and list. Write a function sort_tuple(). Input to the
function is the list of tuples entered by the user. Output from the function is a
sorted list according to the condition - sorted in increasing order by the last
element in each tuple.
e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields
[(2, 2), (1, 3), (3, 4, 5), (1, 7)]

Solution:
1a.

print("Enter list elements (type 'end' to stop)")

temp = ""

user_list = []

#start of loop

while(temp != "end"):

temp = input()

if(temp != "end"):

user_list.append(int(temp))

#end of loop
print("Your list is :: ", user_list)

user_list.sort()

print("After sorting :: ", user_list)

1b.
def tuple_sort(myList):

temp = ()

for i in range(len(myList)):

for j in range(len(myList) - i - 1):

if(myList[j][1] > myList[j+1][1]):

temp = myList[j]

myList[j] = myList[j+1]

myList[j+1] = temp

return myList

myTuple = ()

myList = []

check = 1

while check == 1:

print("Enter Tuple (Separate with ',')")

myTuple = [int(x) for x in input().split(",")]

myList.append(myTuple)

check = int(input("Continue? (1)"))

print("List : " , myList)

myList = tuple_sort(myList)

print("On sorting : " , myList)


Additional Questions (Optional):
1. Animate any object to move across the screen in any manner. Use
Pygame. Pygame uses tuples extensively for screen co-ordinates
representation.
PyGame Steps:
a. Initialize pygame
b. Set the display window size
c. Set the background colour of the window
d. Load the image
e. Blit the image on the display window at the initial (x.y) e.g 10,10
f. Set a direction flag to indicate which co-ordinate to update.
g. Create an infinite loop to display the image continuously.
h. Adjust/increment the position of the image according to the
window size and change the direction if it reaches the end.
i. Set a clock and tick option to wait for sometime to avoid fast
display change
j. Inside the while loop, write code to quit in case of close button
click.
To start with use the anim_template.py from the course classoom, which
has the structure of a pygame animation program. Fill the sections to get a
animation display.
2. Get a list of number from the user (unsorted). Construct max and min
heap from the unsorted list and output the list for min and max heap.

Result:
Ex. No : 1 Title : Lists and Tuples
Program (5)
Coding Conventions (2)
Output (3)
Total (10)
Comments: Signature:
Experiment 2
Dictionaries and Strings
Graded Questions:

2a) Finding the most popular friend from dictionaries

Individual Student Friend Rating Score Dictionaries, (Construct a min of


10 student dictionaries)
Score 1 is lowest and Score of 5 is highest. Every student rates all the
other students. So each dictionary has 9 elements.

Example with 3 students,


sam_friends = {“Bob”:3, “Raj”:5}
bob_friends = {“Sam”:5,”Raj”:1}
raj_friends = {“Sam”:3,”Bob”:5}

Find who has the highest score and that student is the most popular
friend. Print the most popular friend and his/her score.

2b) Get a string as input from the user and the sub string to be searched also
from the user. Find and list the index positions of the sub string and also the
number of occurrences of the sub string.
Solution:

frnd={"person 1":{"person 2":2,"person 3":3,"person 3":4,"person 4":5,"person


5":4,"person 6":4,"person 7":4,

"person 8":4,"person 9":4,"person 10":4},

"person 2": {"person 1": 2, "person 3": 3, "person 3": 4, "person 4": 5,
"person 5": 4, "person 6": 4,

"person 7": 4, "person 8": 4, "person 9": 4, "person 10": 4},

"person 3":{"person 2":2,"person 3":3,"person 1":4,"person 4":5,"person


5":4,"person 6":4,"person 7":4,

"person 8":4,"person 9":4,"person 10":4},

"person 4":{"person 2":2,"person 3":3,"person 3":4,"person 1":5,"person


5":4,"person 6":4,"person 7":4,

"person 8":4,"person 9":4,"person 10":4},

"person 5":{"person 2":2,"person 3":3,"person 3":4,"person 4":5,"person


1":4,"person 6":4,"person 7":4,

"person 8":4,"person 9":4,"person 10":4},

"person 6":{"person 2":2,"person 3":3,"person 3":4,"person 4":5,"person


5":4,"person 1":4,"person 7":4,

"person 8":4,"person 9":4,"person 10":4},

"person 7":{"person 2":2,"person 3":3,"person 3":4,"person 4":5,"person


5":4,"person 6":4,"person 1":4,

"person 8":4,"person 9":4,"person 10":4},

"person 8":{"person 2":2,"person 3":3,"person 3":4,"person 4":5,"person


5":4,"person 6":4,"person 7":4,

"person 1":4,"person 9":4,"person 10":4},

"person 9":{"person 2":2,"person 3":3,"person 3":4,"person 4":5,"person


5":4,"person 6":4,"person 7":4,

"person 8":4,"person 1":4,"person 10":4},


"person 10":{"person 2":2,"person 3":3,"person 3":4,"person 4":5,"person
5":4,"person 6":4,"person 7":4,

"person 8":4,"person 9":4,"person 1":4}

res={"person 1":0,"person 2":0,"person 3":0,"person 4":0,"person 5":0,"person


6":0,"person 7":0,"person 8":0

, "person 9": 0,"person 10":0}

for x in frnd:

for y in frnd[x]:

if y=='person 1':

res["person 1"]+=frnd[x][y]

if y=='person 2':

res["person 2"]+=frnd[x][y]

if y=='person 3':

res["person 3"]+=frnd[x][y]

if y=='person 4':

res["person 4"]+=frnd[x][y]

if y=='person 5':

res["person 5"]+=frnd[x][y]

if y=='person 6':

res["person 6"]+=frnd[x][y]

if y=='person 7':

res["person 7"]+=frnd[x][y]

if y=='person 8':

res["person 8"]+=frnd[x][y]
if y=='person 9':

res["person 9"]+=frnd[x][y]

if y=='person 10':

res["person 10"]+=frnd[x][y]

m=0

for y in res:

if m<res[y]:

m=res[y]

print("Maximum score person is : ",(max(res)))

2b.a=input("Enter the String : ")

b=input("Enter the substring to search : ")

for x in b:

if x in a:

print(x," positions is : ",[pos for pos,char in enumerate(a) if


char==x],"count : ",a.count(x))
Additional Questions:
1. Represent a matrix as nested lists. Get number of rows, number of columns
and input elements from the user and represent it as matrix.

Example:
Matrix

can be represented as
mtx = [ [0,0,0,1,0], [0,0,0,0,0], [0,2,0,0,0], [0,0,0,0,0], [0,0,0,3,0] ]
Access rows and elements and print the same. Also, since the matrix is a sparse
matrix, represent it using a dictionary. Construct the dictionary.
Example
mtx = {(0,3): 1, (2, 1): 2, (4, 3): 3}
a. The dictionary has entries for non-zero elements
b. Key is a tuple that holds the row and column index
c. Value is the element
2. Get a string from the user. Preprocess the string obtained using Porter
Stemming algorithm

Result:

Ex. No : 2 Title : Dictionaries and


Strings
Program (5)
Coding Conventions (2)
Output (3)
Total (10)
Comments: Signature:
Experiment 3
Classes
Graded Questions:

3a) Define a class named “Time”, with instance attributes hours, minutes and
seconds. The class consists of below method, apart from constructor
input_values() – Gets the values of attributes from the user.
print_details() – Prints the values of the attributes

Overload the operators “+” and “-“ to add and subtract the corresponding
attribute values and print accordingly.

For example creating two instances t1 and t2 for “Time” class with attribute
values as below,

Instance Hours Minutes Seconds


t1 12 10 50
t2 10 7 32

then, t1+ t2 should print 22:18:22 and t1-t2 should print 2:3:18

Another example,

Instance Hours Minutes Seconds


t1 20 18 31
t2 14 53 12

then, t1+ t2 should print 11:11:43 and t1-t2 should print 5:25:19

Assume 24 hours clock. Ignore days manipulation.

3b) Write a parent class “Polygon”. This class has two attributes
no_of_sides - represent the number of sides . This is passed as argument to the
constructor when the object is getting created.
sides – is a list representing the value of the sides, initialise the value of sides to
0 in constructor
The class has two methods
input_sides() – Gets the sides from the user. This method would display
messages like
“Enter the value for side1”
“Enter the value for side2”
….
“Enter the value for siden”
and gets the values for the sides from the user and populates the list.
print_sides() – Prints the values of the sides
Create a child class called Triangle, that calls the Parent class constructor with 3
as the number of sides. The child class has one additional method “findArea”,
that finds the area of the triangle using the formula – (side1+side2+side3)/2

Solution
3a.

class Time:

def input_values(self):

self.Hours=int(input("Enter the hour : "))

self.Minutes=int(input("Enter the Minutes : "))

self.Seconds=int(input("Enter the Seconds : "))

def print_detals(self):

print(self.Hours,":",self.Minutes,":",self.Seconds)

def __add__(self, other):

Time.Hours = self.Hours + other.Hours

Time.Minutes = self.Minutes + other.Minutes

Time.Seconds = self.Seconds + other.Seconds

while Time.Seconds>60:

Time.Minutes+=1

Time.Seconds-=60

while Time.Minutes>60:

Time.Hours+=1
Time.Minutes-=60

while Time.Hours>24:

Time.Hours-=24

return Time()

def __sub__(self, other):

Time.Hours = self.Hours - other.Hours

Time.Minutes = self.Minutes - other.Minutes

Time.Seconds = self.Seconds - other.Seconds

while Time.Seconds<0:

Time.Minutes-=1

Time.Seconds+=60

while Time.Minutes<0:

Time.Hours-=1

Time.Minutes+=60

while Time.Hours<0:

Time.Hours+=1

return Time()

a=Time()

a.input_values()

b=Time()

b.input_values()

c=Time()

c=a+b

c.print_detals()
d=Time()

d=a-b

d.print_detals()

3b.

class Polygon:

def __init__(self, no_of_sides):

self.n = no_of_sides

self.sides = [0 for i in range(no_of_sides)]

def inputSides(self):

self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]

def dispSides(self):

for i in range(self.n):

print("Side",i+1,"is",self.sides[i])

class Triangle(Polygon):

def __init__(self):

Polygon.__init__(self,3)

def findArea(self):

a, b, c = self.sides

area = (a + b + c) / 2

print('The area is ',area)

p=Polygon(4)

p.inputSides()

p.dispSides()

t=Triangle()
t.inputSides()

t.findArea()
Additional Question (Optional):

1. Create a class Adder with two user defined methods listAdd() and dictAdd(),
that are used to add two lists and two dictionaries respectively.
Maintain the count of objects/instances created for this class. Whenever the
instance is created, a message is displayed to the user, saying <n>th object
instance of Adder class is created.
Create 3 instances of this class and demonstrate the functionalities.

1. Write a parent class “Bank_Acount”. This class has below attributes


Account ID ,AccountHolderName, Balance

The class has three methods


input_values() – Gets the values of attributes from the user.
print_details() – Prints the values of the attributes
computeDraftLimit() – Computes and prints draft limit value , which is 90%
of balance amount.

Create a child class called “Current_Account”. Apart from the attributes


from the parent class, this child class has two additional attributes –
OverDraftLimit, WaiverBalance.

The child class overrides the computeDraftLimit() method to compute and


prints draft limit value , which is 120% of balance amount.

Create 2 instances – one of parent and one of child class and demonstrate the
functionalities.

Result:

Ex. No : 3 Title : Classes


Program (5)
Coding Conventions (2)
Output (3)
Total (10)
Comments: Signature:
Experiment 4
File Handling
Graded Questions:

4 Python uses the # character to mark the beginning of a comment. The


comment ends at the end of the line containing the # character. In this
exercise, you will create a program that removes all of the comments from a
Python source file. Check each line in the file to determine if a # character is
present. If it is then your program should remove all of the characters from the
# character to the end of the line (we’ll ignore the situation where the
comment character occurs inside of a string). Save the modified file using a
new name that will be entered by the user. The user will also enter the name
of the input file. Ensure that an appropriate error message is displayed if a
problem is encountered while accessing the files.

Solution :

import re

in1=input("Enter file 1 name:")

in2=input("Enter file 2 name:")

try:

fn1=open(in1,'r')

fn2=open(in2,'w')

for line in fn1:

x=re.search('#',line)

if x!=None:

str=line[0:x.start()]

str=str+'\n'

fn2.writelines(str)

else:

fn2.writelines(line)
print("comments removed successfully")

except FileNotFoundError:

print("File not found")

finally:

fn1.close()

fn2.close()

print("files are closed")


Additional Question (Optional):

1. Files that have to be ready for the program – vocab.txt, stopwords.txt and
book.txt. The file vocab.txt has a list of words. The file book.txt has a
paragraph or a short story. The file stopwords.txt has the common words like
- is, was, are, their, her, his etc. Your program should
a. Remove the stop words from the content book.txt, referring to
stopwords.txt.
b. Find words from book.txt that are in vocab.txt. Find the frequency of
occurrence of each word.
c. Find the words from book.txt that are not in vocab.txt. List the words.
Ask the user if these words could be added to vocab.txt.
d. If the user enters yes, append the new words to vocab.txt, else end the
program.
2. Given a file name along with fully qualified path, find the inode information
of the file.

Result:

Ex. No : 4 Title : File Handling


Program (5)
Coding Conventions (2)
Output (3)
Total (10)
Comments: Signature:
Experiment 5
Threads
Graded Questions:

5. Write a Python program to determine in a local network which


addresses/computers are active.Get a list of ip addresses from the user(each
ip address entered as a string). Every time we would have to wait a few
seconds for the return values. A solution without threads is highly
inefficient, because the script will have to wait for every ping.

Solution:

import threading
import os

class myThread (threading.Thread):


def __init__(self, threadID, name, counter):
threading.Thread.__init__(self)
self.threadID = threadID
self.name = name
self.counter = counter
def run(self):
print( "Starting " + self.name)
pinger(self.name)
print( "Exiting " + self.name)

def pinger(hostname) :
response = os.system("ping " + hostname)
if response == 0:
print( hostname, 'is up!')
else:
print( hostname, 'is down!')

iplist = []
thread = []

n = int(input("Enter number of IP's : "))


for i in range(0,n) :
iplist.append(input("Enter IP Address [%d]: " % i ))
thread.append(myThread(i, iplist[i], i))

for i in range(0,n) :
thread[i].run()
Additional Question (Optional):

1. Get a list of URLs from user. , Connect to the URL of a website, and
print out the first 1024 bytes of the page. Use threads for each url
connection.

Result:

Ex. No : 5 Title : Threads


Program (5)
Coding Conventions (2)
Output (3)
Total (10)
Comments: Signature:
Experiment 6
Sockets
Graded Questions:

6. Write a TCP/IP server and client program. It is a echo client program. The
message typed by the client should be echoed back to the client by the
server. Each client connection should be handled by a thread.

Solution:
server
import socket
import _thread

def echoer(c, addr):


print('Got connection from', addr)
msg = c.recv(1024)
print("Sending message to : ", addr)
c.send(msg)
c.close()

s = socket.socket()
host = socket.gethostname()
port = 12345
s.bind((host, port))

s.listen(5)
while True:
c, addr = s.accept()
_thread.start_new_thread(echoer , (c, addr))
Client:
import socket

s = socket.socket()
host = socket.gethostname()
port = 12345

s.connect((host, port))
flag = 1
while(flag == 1):

sendMessage = input("Enter Message")


if(sendMessage == "exit"):
flag = 0
else:
s.send(sendMessage.encode())
msg = s.recv(1024)
print("Message from server : " + msg.decode())

s.close
Additional Question (Optional):

1. Implement a UDP server and client program. It is a echo client program. The
message typed by the client should be echoed back to the client by the
server. Each client connection should be handled by a thread.

Result:

Ex. No : 6 Title : Sockets


Program (5)
Coding Conventions (2)
Output (3)
Total (10)
Comments: Signature:
Experiment 7
CGI Scripts
Graded Questions:

7. Create a web application which allows the user to enter two words(use text
box) and checks whether they are anagrams or not. Display ‘anagram’ if true
else display ‘not anagram’
Note: anagram- a word, phrase, or name formed by rearranging the letters of
another, such as spar, formed from rasp.

Solution:
#HTML code
get.html
<html>
<body>
<form action=\cgi-bin\ana.py>
First name : <input type="text" name="str1" /><br><br>
second name : <input type="text" name="str2" /><br><br>
<input type="button" name="submit" ><br><br>
</form>
<body>
<html>
#ana.py
#!c:/python2.7
print("Content-Type: text/html")
print()
import cgi,cgitb
cgitb.enable() #for debugging
form = cgi.FieldStorage()
f_str = sorted(form.getvalue('str1'))
s_str = sorted(form.getvalue('str2'))
if s_str==f_str:
print "strings are anagrams"
else:
print "strings are not anagrams"
Additional Question (Optional):

1. Write a CGI script to display images selected and the index of the
image.Write a local server that processes the CGI scripts.

Result:

Ex. No : 7 Title : CGI Scripts


Program (5)
Coding Conventions (2)
Output (3)
Total (10)
Comments: Signature:
Experiment 8
GUI application using
TKinter
Graded Questions:

7. Write a tkinter program to edit the phone list. Create the below form. This
application requires creating a SQLite table called “PhoneList” with
Phone_number (Primary Key) and Name as the columns.

Initial Display – Name and Phone are displaying the first record. Records from
the table are listed in the list box below. List box should have scroll bar.

Add – Tries to add the entry in the “Name” and “Phone” fields to the database.
Update – Tries to update the name (as typed in the “Name” text box) for the
phone number in the “Phone” text box.

Delete – Select an item from the list box. The details should be displayed in the
Name and Phone text boxes. After selecting an item if the Delete button is
clicked, the row is removed from the table and the result is displayed to the
user in a separate alert box.

Load – Refreshes the list box display from the entries in the data base.

Solution

from tkinter import *

fr=Frame()
fr.pack()

d =
{"Sam":123,"Linda":456,"Paulman":563,"Cay":789,"Horstmann":6174,"Cor
nell":234,"Ranjan":2788,"Sandy":234}

l1=Label(fr,text="Name")
l1.pack(side='top')
e1=Entry(fr)
e1.pack(side='top')

l2=Label(fr,text="phone")
l2.pack(side='top')
e2=Entry(fr)
e2.pack(side='top')

def h1():
global e1,e2
lst.insert('end',e1.get())
lst.insert('end',e2.get())

def h3():
e1.delete(0,'end')
e2.delete(0,'end')

def h5(event):
label = lst.get(ACTIVE) # on list click
print(label)
ph = d.get(label)
e1.config(text=label)
e2.config(text=ph)

b1=Button(fr,text="add",command=h1)
b3=Button(fr,text="delete",command=h3)
b1.pack(side='top')
b3.pack(side='top')
'''b4=Button(fr,text="load",command=h4)
b4.pack(side='left')'''

lst=Listbox(fr)
scrll=Scrollbar(fr)
scrll.config(command=lst.yview)
lst.config(yscrollcommand=scrll.set)
scrll.pack(side='right')
lst.pack(side='left')
lst.bind('<Double-1>',h5)

for k,v in d.items():


lst.insert('end',k)
lst.insert('end',v)

fr.mainloop()
Result:

Ex. No : 8 Title : GUI application


using TKinter
Program (5)
Coding Conventions (2)
Output (3)
Total (10)
Comments: Signature:
Experiment 9
Databases
Graded Questions:

8. Create the below table in SQLite. Perform insert, update and delete rows
depending on user choice.Write separate python script for table creation.
Write additional script for the above actions, based on user input.

Solution:
import sqlite3
import os
import sys

db=sqlite3.connect("yada.db")
iterator=db.cursor()

def createTables():
try:
iterator.execute("create table Books (BookID text PRIMARY KEY, titleID
text not null, location text not null, genre text )")
iterator.execute("create table Titles (titleID text not null, title text not null,
ISBN text not null, publisherID text not null, publicationYear text, foreign
key(titleID) references Books(titleID))")
iterator.execute("create table publishers (publisherID text not null, name
text not null, streetAdd text, suiteno text, zip text, foreign key(publisherID)
references Titles(publisherID))")
iterator.execute("create table AuthorTit (authorTitID text not null, authID
text not null, titleID not null, foreign key(titleID) references Titles(titleID))")
iterator.execute("create table authors (authID text not null , firstName text
not null, middleName text , lastName text , foreign key(authID) references
AuthorTit(authID))")
iterator.execute("create table zipCodes (zipCodeID text not null , city text,
state text, zipcode text, foreign key(zipCodeID) references publishers(zip))")
db.commit()
except sqlite3.OperationalError:
pass
finally:
print "Tables have been created"

def insertInto(tID):
if(tID==0):
bookID=raw_input("Enter BookID? ")
titleID=raw_input("Enter titleID? ")
location=raw_input("Enter location? ")
genre=raw_input("Enter genre? ")
try:
iterator.execute("insert into Books values (?,?,?,?)",
(bookID,titleID,location,genre))
choice=raw_input("Are you sure (Yes/No) ?")
if choice=="Yes" or choice=="YES" or choice=="yes": db.commit()
else: db.rollback()
except sqlite3.IntegrityError:
print "Please enter a UNIQUE Primary key or foriegn Key"
elif(tID==1):
titleID=raw_input("Enter titleID? ")
title=raw_input("Enter title? ")
ISBN=raw_input("Enter ISBN? ")
publisherID=raw_input("Enter publisherID? ")
publicationYear=raw_input("Enter publicationYear? ")
try:
iterator.execute("insert into Titles values (?,?,?,?,?)",
(titleID,title,ISBN,publisherID,publicationYear))
choice=raw_input("Are you sure (Yes/No) ?")
if choice=="Yes" or choice=="YES" or choice=="yes": db.commit()
else: db.rollback()
except sqlite3.IntegrityError:
print "Please enter a UNIQUE Primary key or foriegn Key"
elif(tID==2):
publisherID=raw_input("Enter publisherID? ")
name=raw_input("Enter name? ")
streetAdd=raw_input("Enter street Address? ")
suiteno=raw_input("Enter Suite Number? ")
zipx=raw_input("Enter Zip? ")
try:
iterator.execute("insert into publishers values (?,?,?,?,?)",
(publisherID,name,streetAdd,suiteno,zipx))
choice=raw_input("Are you sure (Yes/No) ?")
if choice=="Yes" or choice=="YES" or choice=="yes": db.commit()
else: db.rollback()
except sqlite3.IntegrityError:
print "Please enter a UNIQUE Primary key or foriegn Key"
elif(tID==3):
authorTitID=raw_input("Enter Author Title ID? ")
authID=raw_input("Enter Author ID? ")
titleID=raw_input("Enter Title ID? ")
try:
iterator.execute("insert into AuthorTit values (?,?,?,?,?)",
(publisherID,name,streetAdd,suiteno,zipx))
choice=raw_input("Are you sure (Yes/No) ?")
if choice=="Yes" or choice=="YES" or choice=="yes": db.commit()
else: db.rollback()
except sqlite3.IntegrityError:
print "Please enter a UNIQUE Primary key or foriegn Key"
elif(tID==4):
authID=raw_input("Enter Author ID? ")
firstName=raw_input("Enter first Name? ")
middleName=raw_input("Enter middle Name? ")
lastName=raw_input("Enter last Name? ")
try:
iterator.execute("insert into authors values (?,?,?,?)",
(authID,firstName,middleName,lastName))
choice=raw_input("Are you sure (Yes/No) ?")
if choice=="Yes" or choice=="YES" or choice=="yes": db.commit()
else: db.rollback()
except sqlite3.IntegrityError:
print "Please enter a UNIQUE Primary key or foriegn Key"
elif(tID==5):
ZipCodeID=raw_input("Enter Zip Code ID? ")
city=raw_input("Enter city? ")
state=raw_input("Enter State? ")
zipCode=raw_input("Enter Zip Code? ")
try:
iterator.execute("insert into zipCodes values(?,?,?,?",
(ZipCodeID,city,state,zipCode))
choice=raw_input("Are you sure (Yes/No) ?")
if choice=="Yes" or choice=="YES" or choice=="yes": db.commit()
else: db.rollback()
except sqlite3.IntegrityError:
print "Please enter a UNIQUE Primary key or foriegn Key"

def selectFromAllTables(tID):
try:
if(tID==0): iterator.execute('select * from Books')
elif(tID==1): iterator.execute('select * from Titles')
elif(tID==2): iterator.execute('select * from publishers')
elif(tID==3): iterator.execute('select * from AuthorTit')
elif(tID==4): iterator.execute('select * from authors')
elif(tID==5): iterator.execute('select * from zipCodes')
print (iterator.fetchall())
except:
print "No such records found"
createTables()
while True:
print "1. Insert into Tables "
print "2. Display All Tables "
print "3. Exit"
subchoice=int(raw_input("Enter choice? "))
if subchoice == 3:
db.close()
break
print "You want to operate on which Table?"
print "1. Books Table"
print "2. Titles Table"
print "3. Publishers Table"
print "4. Author Table"
print "5. Authors Table"
print "6. ZipCodes Table"
choice=int(raw_input("Enter the table? ")) - 1
if(subchoice==1): insertInto(choice)
elif(subchoice==2): selectFromAllTables(choice)
else: print "Try Again"
Additional Question (Optional):

1. Write a python program to query the metadata of a database


a. List all the tables in the database
b. For each table, list all the column names, description and data types

Result:

Ex. No : 9 Title : Databases


Program (5)
Coding Conventions (2)
Output (3)
Total (10)
Comments: Signature:

You might also like