Lab Manual - Old
Lab Manual - Old
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:
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.
2. Type
python filename.py
Solution:
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 : "))
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 : "))
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("\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.
Sample Output:
Solution:
print("Zellers algorithm to return the day of the week for any year")
month = month - 2
if month == 0:
month = 12
year = year - 1
month = 11
year = year - 1
W = (13*month - 1)//5
X = year//4
Y = cent//4
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:
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
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):
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)):
else:
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.
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()
1b.
def tuple_sort(myList):
temp = ()
for i in range(len(myList)):
temp = myList[j]
myList[j] = myList[j+1]
myList[j+1] = temp
return myList
myTuple = ()
myList = []
check = 1
while check == 1:
myList.append(myTuple)
myList = tuple_sort(myList)
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:
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:
"person 2": {"person 1": 2, "person 3": 3, "person 3": 4, "person 4": 5,
"person 5": 4, "person 6": 4,
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]
for x in b:
if x in a:
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:
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,
then, t1+ t2 should print 22:18:22 and t1-t2 should print 2:3:18
Another example,
then, t1+ t2 should print 11:11:43 and t1-t2 should print 5:25:19
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):
def print_detals(self):
print(self.Hours,":",self.Minutes,":",self.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()
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:
self.n = no_of_sides
def inputSides(self):
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
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.
Create 2 instances – one of parent and one of child class and demonstrate the
functionalities.
Result:
Solution :
import re
try:
fn1=open(in1,'r')
fn2=open(in2,'w')
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:
finally:
fn1.close()
fn2.close()
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:
Solution:
import threading
import os
def pinger(hostname) :
response = os.system("ping " + hostname)
if response == 0:
print( hostname, 'is up!')
else:
print( hostname, 'is down!')
iplist = []
thread = []
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:
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
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):
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:
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:
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
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)
fr.mainloop()
Result:
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):
Result: