Project File Cse
Project File Cse
1
INDEX
SR NO CONTENTS Pg-no
1. Overview of Python 3
2. Classes and Objects 4
3. Inheritance 21
4. Linear List 47
5. Stacks and Queues 60
6. File Handling 73
7. Exception 115
8. SQL 133
9. Generator functions 149
10. Random module 156
2
OVERVIEW OF PYTHON
PYTHON was created by GUIDO VAN ROSSUM when he was working at CWI
(Centrum Wiskunde & Information) which is a National Research Institute
for Mathematics and Computer Science in Netherlands. The language was
released in 1991. Python got its name from a BBC comedy series from
seventies – “Monty Python’s Flying Circus”. Python can be used to follow
both Procedural approach and Object Oriented approach of programming.
It is free to use.
3
CLASSES &
OBJECTS
4
Question 1:
Create a class TOURIST in python having following specifications:
Instance attributes:
cno - to store cab no.
Methods:
init() - to assign initial values of ctype as ‘A’ and cno. As ‘0000’
ctypeperkm
A 20
B 18
C 15
registercab() - to allow administrator to enter values for cno and ctype and
call citycharges() to assign perkm
diplay() - to allow the user to enter the value of distance and display
cno,ctype,perkm*distance(as amount ) on screen
5
CODE:
class TOURIST:
def __init__(self):
self.cno=0000
self.ctype="A"
self.perkm=0
self.distance=0
def registercab(self):
self.citycharges()
def citycharges(self):
if self.ctype=="A":
self.perkm=20
elif self.ctype=="B":
self.perkm=18
elif self.ctype=="C":
self.perkm=15
def display(self):
self.distance=input("enter distance:")
T1=TOURIST()
T1.registercab()
6
T1.display()
Output:
7
Question 2:
# static method
Code:
class Student:
scount=0
def __init__(self):
self.rno=0
self.name="na"
self.marks=0
Student.scount+=1
def input(self):
self.name=raw_input("enter name:")
self.marks=input("enter marks:")
def output(self):
@staticmethod
def show_count():
8
print "total no. of students=",Student.scount
s1=Student()
s2=Student()
s3=Student()
s1.input()
s2.input()
s3.input()
s1.output()
s2.output()
s3.output()
Student.show_count()
9
Output:
10
Question 3:
# class attributes
Code:
class Student:
def __init__(self):
self.rno=0
self.name="na"
self.__marks=0
def input(self):
self.name=raw_input("enter name:")
self.__marks=input("enter marks:")
def output(self):
s1=Student()
class
print __name__#returns the default name of the top level section of a program
11
print Student.__module__#returns the module name in which the class is
defined
output:
12
Question 4:
# attr methods
Code:
class Employee:
empcount=0
def __init__(self, name, salary):
self.name=name
self.salary=salary
Employee.empcount+=1
def display_count(self):
print "no. of employees is",Employee.empcount
def display_employee(self):
print "Name of Eployee:",self.name
print "Salary of Eployee:",self.salary
#outside class
emp1=Employee("Chetan", 20000)
emp2=Employee("anurag", 25000)
#hasattr
if hasattr (emp1,"age"):
print "instance emp1 has attribute age"
else:
print "instance 'emp1' has no attribute age"
#getattr
13
print "value of attribute 'name' in instance 'emp1' is", getattr (emp1,'name')
#setattr
setattr (emp1,'name', 'Chetan Singh')
print "value of attribute 'name' in instance 'emp1' is", getattr (emp1,'name')
#delattr
delattr (emp1,'name')
if hasattr (emp1,"name"):
print "instance 'emp1' has attribute 'name'"
else:
print "instance 'emp1' has no attribute 'name'"
if hasattr (emp2,"name"):
print "instance 'emp2' has attribute 'name'"
else:
print "instance 'emp2' has no attribute 'name'"
14
Output:
15
Question 5:
# private members
Code:
class Sports:
No_of_objects=0
def __init__(self):
self.__Scode=1001 #private instance variable
self.__Sname="Hockey" #accessible inside class
self.__Fees=600.0 #inaccessible outside class
self.__Duration=70 #not available to objects
Sports.No_of_objects+=1 #Class variable accessed using class name
def __Assignfee(self): #private instance method not availalve to objects
if self.__Sname=="Table Tennis":
self.__Fees=1600.0
elif self.__Sname=="Cricket":
self.__Fees=1000.0
elif self.__Sname=="Swimming":
self.__Fees=3000.0
elif self.__Sname=="Football":
self.__Fees=2500.0
def Newsport(self):
self.__Scode=input("Enter the Sport Code")
self.__Sname=raw_input("Enter Sport Name")
self.__Duration=input("Enter Duration")
self.__Assignfee() #private class method called using 'self' keyword
inside class
16
def Showsport(self):
print "The Code of the Sport is",self.__Scode
print "The Name of the Sport is",self.__Sname
print "The Duration of the Sport is",self.__Duration
print "The Fees for the Sport is",self.__Fees
#outside class
S1=Sports()
#print Sports.__Scode (inaccessible- gives error)
S1.Newsport()
S1.Showsport()
# S1.__Assignfee() (inaccessible- gives error)
17
Output:
18
Question 6
#Class attribute methods
#program to illustrate the use of attr methods
class emp:
def __init__(self,n,s):
self.name=n
self.sal=s
def show(self):
print self.name
print self.sal
print hasattr(e1,"sal")
print hasattr(e1,"salary")
print e1.name
setattr(e1,"name","amit jain")
print e1.name
print e1.desig
print getattr(e1,"sal")
19
delattr(e1,"sal")
print hasattr(e1,"sal")
Output
20
INHERITANCE
21
#Single Inheritance
class Person:
def __init__(self,n,a):
self.name=n
self.age=a
class Employee(Person):
def __init__(self,n,a,sal):
Person.__init__(self,n,a)
self.salary=sal
def show(self):
print self.name,self.age,self.salary
emp1=Employee("Amit",25,25000)
emp1.show()
print emp1.name,emp1.age,emp1.salary
22
Output
23
#Multiple Inheritance
class A:
def __init__(self,x):
self.a=x
class B:
def __init__(self,y):
self.b=y
class C(A,B):
def __init__(self,x,y,z):
A.__init__(self,x)
B.__init__(self,y)
self.c=z
#outside class
C1=C(5,15,20)
print C1.a,C1.b,C1.c
24
Output
25
#Multilevel Inheritance:
class Medicine:
def __init__(self):
self.category=" "
self.mfg=" "
self.cmp=" "
def inp(self):
def show(self):
class Capsules(Medicine):
def __init__(self):
Medicine.__init__(self)
self.Capsule_name=" "
self.Volume_label=" "
def Inp(self):
print "Capsule:"
self.inp()
def Output(self):
print "Capsule:"
self.show()
class Antibiotic(Capsules):
def __init__(self):
Capsules.__init__(self)
self.Dosage_units=0
self.side_effects=" "
def Input(self):
print "Antibiotic:"
self.Inp()
def output(self):
print "Antibiotic:"
self.Output()
a1=Antibiotic()
a1.Input()
27
a1.output()
output
28
#Hierarchical Inheritance
class person:
def __init__(self,n,a):
self.name=n
self.age=a
class employee(person):
def __init__(self,n,a,sal):
person.__init__(self,n,a)
self.salary=sal
def show(self):
print self.name,self.age,self.salary
class student(person):
def __init__(self,n,a,m):
person.__init__(self,n,a)
self.marks=m
def show(self):
print self.name,self.age,self.marks
emp1=employee("amit",25,25000)
emp1.show()
print emp1.name,emp1.age,emp1.salary
29
std1=student("amit",16,83)
std1.show
output
30
#Hybrid Inheritance
class Person:
def __init__(self):
self.name=" "
self.c_no=0
def inp(self):
def show(self):
class Teacher(Person):
def __init__(self):
Person.__init__(self)
self.t_id=0
def Inp(self):
print "Teacher:"
self.inp()
def Output(self):
print "Teacher:"
self.show()
31
class Student(Person):
def __init__(self):
Person.__init__(self)
self.r_no=0
self.a_no=0
self.mks=0
def Input(self):
print "Student:"
self.inp()
def out(self):
print "Student:"
self.show()
class School(Teacher,Student):
def __init__(self):
Person.__init__(self)
Student.__init__(self)
self.s_id=0
32
self.s_name=" "
def getinfo(self):
self.Inp()
self.Input()
def Show(self):
self.Output()
self.out()
O1=School()
O1.getinfo()
O1.Show()
33
Output
34
# q-17 ncert
class furniture:
def __init__(self,Type,Model):
self.Type=Type
self.Model=Model
def gettype(self):
print "Type:"
return self.Type
def getmodel(self):
print "Model:"
return self.Model
def show(self):
print "Type:",self.Type,";","Model:",self.Model
class sofa(furniture):
def __init__(self,t,m,n,cost):
furniture.__init__(self,t,m)
self.nos=n
self.cost=cost
def getseats(self):
return self.nos
def getcost(self):
35
print "Cost:"
return self.cost
def show(self):
furniture.show(self)
print "Cost=",self.cost
s1=sofa("Wooden","XYZ",4,3000)
print s1.gettype()
print s1.getmodel()
print s1.getcost()
s1.show()
36
Output
37
#Q-18 ncert
class trainer:
def __init__(self,n,tid):
self.name=n
self.tid=tid
def getname(self):
return self.name
def gettid(self):
return self.tid
class learner:
def __init__(self,n1,lid):
self.lid=lid
self.lname=n1
def getlname(self):
return self.lname
def getlid(self):
return self.lid
38
class institute(learner,trainer):
def __init__(self,n,tid,n1,lid,n3,icode):
learner.__init__(self,n1,lid)
trainer.__init__(self,n,tid)
self.iname=n3
self.icode=icode
def getiname(self):
return self.iname
def geticode(self):
return self.icode
print i1.getname()
print i1.geticode()
print i1.getlname()
print i1.getlid()
print i1.getiname()
print i1.geticode()
39
output
40
#Q-21 ncert
class employee:
def __init__(self):
self.empno=0
self.empname=""
self.empno=input("enter empno")
self.empname=raw_input("enter empname")
def printdata(self):
print "Empno:",self.empno,";Empname:",self.empname
class payroll(employee):
def __init__(self):
employee.__init__(self)
self.salary=0
def inputdata(self):
employee.getdata(self)
def outputdata(self):
employee.printdata(self)
print "Salary:",self.salary
class leave(payroll):
def __init__(self):
self.nod=0
41
def acceptdata(self):
payroll.inputdata(self)
def showdata(self):
payroll.outputdata(self)
print "Leaves",self.nod
l1=leave()
l1.acceptdata()
l1.showdata()
42
Output
43
#Overriding methods
class Person:
def __init__(self):
self.name=" "
self.c_no=0
def inp(self):
print "Person:"
def show(self):
class Student(Person):
def __init__(self):
Person.__init__(self)
self.r_no=0
self.mks=0
def inp(self):
print "Student:"
Person.inp(self)
def show(self):
44
Person.show(self)
s1=Student()
s1.inp()
s1.show()
p1=Person()
p1.inp()
p1.show()
45
Output
46
LINEAR
LIST
47
#Linear Search
l=[]
for i in range(0,n):
l.append(val)
l.sort()
f=0
if key>l[len(l)-1]:
for j in l:
if j==key:
pos=l.index(j)+1
break
elif j>key:
break
48
output
49
#Binary Search
l=[]
for i in range(0,n):
l.append(val)
l.sort()
def bsearch(l,item):
lb=0
ub=len(l)-1
while lb<=ub:
mid=(lb+ub)/2
if item==l[mid]:
return mid
elif item>l[mid]:
lb=mid+1
ub=mid-1
else:
return -1
ind=bsearch(l,item)
if ind==-1:
50
print "Value not present in the list:"
else:
Output
51
#Bubble Sort
l=[]
for j in range(0,n):
l.append(val)
def bubblesort(l):
for p in range(len(l)-1,0,-1):
t=0
for i in range(0,p):
if l[i]>l[i+1]:
t=l[i]
l[i]=l[i+1]
l[i+1]=t
bubblesort(l)
52
output
53
#Selection Sort
def selsort(l):
for i in range(len(l)):
least=i
for k in range(i+1,len(l)):
if l[k]<l[least]:
least=k
t=l[least]
l[least]=l[i]
l[i]=t
l=[]
for j in range(0,n):
l.append(val)
selsort(l)
54
output
55
#Insertion Sort
def insertionsort(l):
for i in range(1,len(l)):
v=l[i]
j=i
l[j]=l[j-1]
j-=1
l[j]=v
l=[]
for j in range(0,n):
l.append(val)
insertionsort(l)
56
output
57
#Insertion using bisect module
import bisect
l=[1,3,5,12,29,36,50]
print l
ind=bisect.bisect(l,item)
bisect.insort(l,item)
print l
output
58
#Deletion using Bisect Module
import bisect
l=[2,8,22,35,43,50]
print l
ind=bisect.bisect(l,item)
del l[ind-1]
print l
output
59
STACKS
&
QUEUES
60
#Program to implement queue using list
q=[]
def addqueue():
a=input("Enter a value:")
q.append(a)
def deleteq():
if len(q)==0:
else:
def showq():
if len(q)==0:
else:
for i in range(0,len(q)):
print q[i]
ans="y"
if ch==1:
addqueue()
elif ch==2:
deleteq()
elif ch==3:
showq()
else:
62
output
63
#Program to implement queue using class
class queue:
q=[]
def addqueue(self):
a=input("Enter a value:")
queue.q.append(a)
def deleteq(self):
if len(queue.q)==0:
else:
def showq(self
):
if len(queue.q)==0:
else:
for i in range(0,len(queue.q)):
print queue.q[i]
ans="y"
64
q1=queue()
if ch==1:
q1.addqueue()
elif ch==2:
q1.deleteq()
elif ch==3:
q1.showq()
else:
65
output
66
# Program to implement stack using list without class
s=[]
def push():
a=input("Enter a value:")
s.append(a)
def pop():
if len(s)==0:
else:
def show():
if len(s)==0:
else:
for i in range(len(s)-1,-1,-1):
print s[i]
ans="y"
print "1.PUSH"
67
print "2.POP"
print "3.DISPLAY"
if ch==1:
push()
elif ch==2:
pop()
elif ch==3:
show()
else:
68
output
69
#Program to implement stack using class
class stack:
def push(self,n):
stack.s.append(n)
def pop(self):
if len(stack.s)==0:
else:
def show(self):
if len(stack.s)==0:
else:
for i in range(len(stack.s)-1,-1,-1):
print stack.s[i]
s1=stack()
ans="y"
print "1.PUSH"
print "2.POP"
70
print "3.DISPLAY"
if ch==1:
s1.push(a)
elif ch==2:
s1.pop()
elif ch==3:
s1.show()
else:
71
output
72
FILE
HANDLING
73
#To print number of characters in a file
fr=open("1.txt","r")
str=fr.read()
print str
print len(str)
fr.close()
output
74
#To print number of vowels
fr=open("1.txt","r")
str=fr.read()
vc=0
l=['a','e','i','o','u','A','E','I','O','U']
for i in str:
if i in l:
vc+=1
fr.close()
output
75
#To print number of '#' in a file
fr=open("1.txt","r")
str=fr.read()
vc=0
for i in str:
if i=='#':
vc+=1
fr.close()
output
76
#To count number of 'a' and 'b' in a file
fr=open("1.txt","r")
str=fr.read()
va=0
vb=0
for i in str:
if i=='a':
va+=1
elif i=='b':
vb+=1
fr.close()
77
output
78
#To replace all spaces by '*' in a file
fr=open("1.txt","r")
str=fr.read()
for i in str:
if i==' ':
print '*',
else:
print i,
fr.close()
########_____or_____########
s=str.replace(' ','*')
print s
output
79
#To print number of lines in a file
fr=open("1.txt","r")
l=fr.readlines()
print l
fr.close()
output
80
#To print file in reverse order
fr=open("1.txt","r")
s=fr.readline()
print s[-1:-len(s)-1:-1]
#___________or_________
for i in range(len(s)-1,-1,-1):
print s[i],
s=fr.readline(3)
print s
fr.close()
output
81
#To print first character of a file
fr=open("1.txt","r")
s=" "
while s:
s=fr.readline()
if len(s)<>0:
print s[0]
fr.close()
Output
82
#To print four character words in a file
fr=open("1.txt","r")
s=fr.read()
l=s.split()
print l
for i in l:
if len(i)==4:
print i
fr.close()
Output
83
#To display the count of his and her in '2.txt' file
fw=open("2.txt","w")
s1="palak has gone to her friends house\n" + "Her friend's name is Ravya\n" +
"Her house is 12km from here\n"
fw.write(s1)
fw.close()
fr=open("2.txt","r")
str=fr.read()
l=str.split()
c1=0
c2=0
for i in l:
if i=="his" or i=="His":
c1+=1
elif i=="Her":
c2+=1
fr.close()
84
Output
85
#To display all words that begin with t or T in reverse
from "3.txt" file
fw=open("3.txt","w")
fw.write(s1)
fw.close()
fr=open("3.txt","r")
str=fr.read()
l=str.split()
for i in l:
if i[0]=="T" or i[0]=="t":
print i[-1:-len(i)-1:-1]
fr.close()
86
Output
87
#To copy lowercase and uppercase vowels from file
'vowels.txt' to LOWER.txt and UPPER.txt
respectively
#To copy lowercase and uppercase vowels from file 'vowels.txt' to LOWER.txt
and UPPER.txt respectively:
fw=open("vowels.txt","w")
fw.write(s1)
fw.close()
fr=open("vowels.txt","r")
fw1=open("UPPER.txt","w")
fw2=open("LOWER.txt","w")
str=fr.read()
lv=['a','e','i','o','u']
uv=['A','E','I','O','U']
for i in str:
if i in uv:
fw1.write(i)
elif i in lv:
fw2.write(i)
fr.close()
fw1.close()
88
fw2.close()
Output
89
#Writing to a text file line by line using writelines()
that operates on lists
n=input("How many lines:")
fw=open("line.txt","a+")
l=[]
for i in range(n):
l.append(s+'\n')
fw.writelines(l)
fw.close()
Output
90
#Writing to a text file using write() function
n=input("How many lines:")
fw=open("lines1.txt","a")
for i in range(n):
fw.write(s+'\n')
fw.close()
Output
91
#Menu based operation on binary file
import os
import pickle
class emp:
def __init__(self):
self.eno=0
self.name="null"
self.sal=0
def input(self):
self.eno=input("enter eno:")
self.name=raw_input("enter name:")
self.sal=input("enter sal:")
def output(self):
print self.eno,self.name,self.sal
def edit(self):
e1=emp()
def append():
fw=open("empb.dat","ab")
e1.input()
pickle.dump(e1,fw)
92
print "object appended to file"
fw.close()
def showall(fname):
fr=open(fname,"rb")
try:
while True:
e1=pickle.load(fr)
e1.output()
except EOFError:
fr.close()
#------------------------------------------------------------------------------------------------
------------------
def showeno():
fr=open("empb.dat","rb")
f=0
try:
while True:
e1=pickle.load(fr)
if e1.eno==n:
e1.output()
f=1
#fr.close()
#break
93
except EOFError:
fr.close()
if f==0:
#------------------------------------------------------------------------------------------------
------------------
def showename():
fr=open("empb.dat","rb")
# print n
f=0
try:
while True:
e1=pickle.load(fr)
if e1.name==n:
e1.output()
f=1
except EOFError:
fr.close()
if f==0:
94
#------------------------------------------------------------------------------------------------
------------------
def showsal():
fr=open("empb.dat","rb")
f=0
try:
while True:
e1=pickle.load(fr)
if e1.sal>=15000:
e1.output()
f+=1
except EOFError:
fr.close()
#------------------------------------------------------------------------------------------------
------------------
def delete():
f=0
try:
while True:
e1=pickle.load(fr)
95
if e1.eno==n:
f=1
else:
pickle.dump(e1,fw)
except EOFError:
fr.close()
fw.close()
os.remove("empb.dat")
os.rename("temp.dat","empb.dat")
if f==0:
else:
showall("empb.dat")
#------------------------------------------------------------------------------------------------
------------------
def update():
fr=open("empb.dat","rb")
fw=open("temp.dat","wb")
96
n=input("enter the eno to be modified:")
f=0
try:
while True:
e1=pickle.load(fr)
if e1.eno==n:
e1.edit()
pickle.dump(e1,fw)
f=1
else:
pickle.dump(e1,fw)
except EOFError:
fr.close()
fw.close()
os.remove("empb.dat")
os.rename("temp.dat","empb.dat")
if f==0:
else:
showall("empb.dat")
97
#------------------------------------------------------------------------------------------------
------------------
def copy():
fr=open("empb.dat","rb")
fw=open("highsal.dat","wb")
f=0
try:
while True:
e1=pickle.load(fr)
if e1.sal>15000:
pickle.dump(e1,fw)
f+=1
except EOFError:
fr.close()
fw.close()
if f==0:
else:
showall("highsal.dat")
98
#------------------------------------------------------------------------------------------------
----------------
def transfer():
fr=open("empb.dat","rb")
fw1=open("highsal1.dat","wb")
fw2=open("temp.dat","wb")
f=0
try:
while True:
e1=pickle.load(fr)
if e1.sal>15000:
pickle.dump(e1,fw1)
f+=1
else:
pickle.dump(e1,fw2)
except EOFError:
fr.close()
fw1.close()
fw2.close()
os.remove("empb.dat")
os.rename("temp.dat","empb.dat")
if f==0:
99
else:
showall("highsal1.dat")
print "-------------------------------------------------------------------------"
showall("empb.dat")
#------------------------------------------------------------------------------------------------
------------------
100
Output
101
102
#Python program to print swapcase
f=open("1.txt","r")
s=f.read()
for i in s:
if i.islower() or i.isupper():
print i.swapcase(),
else:
print i,
Output
103
#Program to join two files
fr=open("2.txt","r")
fr2=open("3.txt","r")
fw=open("4.txt","w")
s=fr.readlines()
s1=fr2.readlines()
fw.writelines(s)
fw.write('\n')
fw.writelines(s1)
fr.close()
fr2.close()
fw.close()
Output
104
#Program to tell pointer index
fr=open("1.txt","r")
print fr.read()
fr.seek(6,0)
print fr.read()
fr.close()
Output
105
#Program to remove a word from file
import os
s=fr.read()
l=s.split()
for i in l:
if i<>n:
fw.write(i+'\n')
fr.close()
fw.close()
os.remove("1.txt")
os.rename("10.txt","1.txt")
106
Output
107
#Creating a dictionary and storing it in binary file
import pickle
fw=open("d1.dat","wb")
for i in range(n):
d={}
k=input("enter key:")
d[k]=v
pickle.dump(d,fw)
fw.close()
fr=open("d1.dat","rb")
d1={}
try:
while True:
d1=pickle.load(fr)
print d1
except EOFError:
fr.close()
108
Output
109
#Creating a dictionary having key and its value stored
in list and storing it in binary file
import pickle
d={}
for i in range(n):
k=input("Enter rollno:")
d[k]=l
fw=open("d3.dat","wb")
pickle.dump(d,fw)
fw.close()
fr=open("d3.dat","rb")
d1={}
try:
while True:
d1=pickle.load(fr)
print d1
except EOFError:
fr.close()
110
Output
111
#Inserting values in a dictionary at a position
specified by the user:
import pickle
import os
fr=open("d1.dat","rb")
fw=open("temp.dat","wb")
d={}
f=0
count=1
d1={}
try:
while True:
if count<>n:
d1=pickle.load(fr)
pickle.dump(d1,fw)
else:
k=raw_input("enter key:")
d[k]=v
pickle.dump(d,fw)
f+=1
except EOFError:
fr.close()
fw.close()
os.remove("d1.dat")
os.rename("temp.dat","d1.dat")
if f==0:
else:
fr=open("d1.dat","rb")
d1={}
try:
while True:
d1=pickle.load(fr)
print d1
except EOFError:
fr.close()
113
Output
114
EXCEPTION
HANDLING
115
#Attribute Error
class emp:
def __init__(self):
self.eno=0
self.ename="null"
def input(self):
self.eno=input("Enter eno:")
self.ename=raw_input("Enter ename:")
def output(self):
try:
e1=emp()
print e1.name
e1.output()
except AttributeError:
else:
116
Output
117
#another example of attribute error
class emp:
def __init__(self):
self.eno=0
self.ename="null"
def input(self):
self.eno=input("enter eno")
self.ename=raw_input("enter ename")
def output(self):
print self.eno,self.ename
try:
e1=emp()
print e1.ename
e1.outputt()
except AttributeError:
else:
118
Output
119
#Program to handle division by zero exception
try:
ans=dividend/divisor
except ZeroDivisionError:
else:
print "ans=",ans
Output
120
#Import Error
try:
p=pow(base,e)
except ImportError:
else:
print "ans=",p
Output
121
#Index Error
try:
print s[1]
print s[9]
except IndexError:
else:
print "string=",s
finally:
Output
122
#Key Error
d=dict()
try:
for i in range(5):
d[k]=v
for i in d.keys(): #d.keys gives all the keys of the dictionary in the form of list
print d[i]
print d[9]
except KeyError:
finally:
123
Output
124
#Program to handle division by zero exception by
explicitly raising it
try:
if divisor==0:
raise ZeroDivisionError
ans=dividend/divisor
print ans
except ZeroDivisionError:
else:
print "ans=",ans
125
Output
126
#Program to handle division by zero exception by
explicitly raising it with a user defined message
try:
if divisor==0:
ans=dividend/divisor
except ZeroDivisionError,e:
print "exception:-",e
else:
print "ans=",ans
127
Output
128
#Program to handle type error exception
try:
sum=n1+n2
except TypeError:
else:
print "sum=",sum
Output
129
#Program to create and raise user defined exception
class MyError(Exception): #'Exception' is the inbuilt base class
pass
err2=MyError
try:
if marks<0:
elif marks>100:
elif marks>40:
else:
except MyError,e: #'except' can take only class name or inbuilt error name
else:
print "Marks=",marks
finally:
130
Output
131
#Program to handle VALUE error exception
try:
sum=n1+n2
except ValueError:
else:
print "sum=",sum
Output
132
SQL
133
SQL QUERIES
Question 1:
Table : Students
135
Question 2:
Table : ACTIVITY
Table : COACH
2 Ravinder 1008
3 Janila 1001
4 Naaz 1003
137
1. CREATE TABLE COMMAND
(EMPNO number (4) NOT NULL PRIMARY KEY, -- Assigning primary key
HRDATE date,
OUTPUT:
Table created
2. INSERT COMMAND
VALUES
OUTPUT:
COMPANY
OUTPUT:
AS
FROM COMPANY ) ;
OUTPUT:
EMPLOY
DEPTCOMM number(4) ,
references COMPANY(EMPNO) ) ;
EMPL
101 10 4000
102 20 2000
103 30 1500
104 30 1500
105 40 1000
106 30 1500
107 40 1000
5. SELECT STATEMENT
SQL> SELECT *
FROM COMPANY ;
OUTPUT:
COMPANY
6. JOIN
WHERE COMPANY.EMPNO=EMPL.EMPNO
FROM COMPANY ;
OUTPUT:
141
ANNUAL SALARY
1140000
900000
240000
240000
660000
240000
660000
FROM COMPANY ;
OUTPUT:
95000
20000
48971
9. GROUPING
FROM COMPANY
GROUP BY JOB ;
OUTPUT:
JOB SAL
________ ____
CEO 95000
MANAGER 75000
SALESMAN 20000
ANALYST 55000
FROM COMPANY ;
OUTPUT:
11.HAVING CONDITION
( DISPLAY JOB WISE SALARY FOR ALL JOBS THAT DO NOT BEGIN WITH ‘A’ HAVING SALARY MORE THAN
50000 DISPLAY IN DESC ORDER OF JOB FROM COMPANY)
FROM COMPANY
GROUP BY JOB
OUTPUT:
JOB SAL
______ _____
CEO 95000
MANAGER 75000
FROM COMPANY
OUTPUT:
EMPNO
_____
143
102
105
107
FROM COMPANY ;
OUTPUT:
SAL
____
96000
76000
21000
21000
56000
21000
56000
WHERE SAL=20000 ;
FROM COMPANY ;
OUTPUT:
SAL
____
95000
144
75000
21000
21000
55000
21000
55000
SQL> SELECT *
FROM COMPANY ;
OUTPUT:
145
SQL> SELECT *
FROM COMPANY ;
OUTPUT:
SQL> SELECT *
FROM COMPANY ;
OUTPUT:
OUTPUT:
Table dropped
20 . CREATE VIEW
SELECT *
FROM EMP ;
OUTPUT:
View created
SQL> SELECT *
FROM V1 ;
147
OUTPUT:
21.
SQL> UPDATE V1
SET SAL=SAL+1000
WHERE EMPNO=102 ;
148
149
# Generator function to return composite numbers upto digit given by
the user
def composite(n):
for i in range(2,n+1):
isprime=True
for j in range(2,i):
if i%j==0:
isprime=False
if isprime==False:
yield i
Output
150
# Program to genetrate the prime numbers upto given number
def prime(n):
for i in range(2,n+1):
isprime=True
for j in range(2,i):
if i%j==0:
isprime=False
if isprime==True:
yield i
Output
151
# Program to find factorial of a number by a generator function
def factorial(x):
for i in range(x):
fac=1
for j in range(1,i+1):
fac=fac*j
yield fac
Output
152
# Program to generate fibonaci series from a generator function
def fibonacci(Max):
a=0
b=1
while a < Max:
yield a
a,b=b,a+b
x=fibonacci(20)
Output
153
# Program to generate square of numbers upto given number
def square(x):
for i in range(x+1):
yield i**2
Output
154
# Program to generate series upto x raised to x
def x_raisedto_x(x):
for i in range(1,x+1):
yield i**i
Output
155
RA DOM
MOD LE
156
print '### WELCOME TO RANDOM MODULE ###'
storeRand = []
def random_random():
randNum = random()
storeRand.append(randNum)
print 'Your random number generated and successfully stored.'
print storeRand
else:
print 'There is already the same number in the directory, run function again to store a different
number.'
print 'Generating a random integer between ', low, 'and ', up, '...'
print randNum
if randNum not in storeRand:
storeRand.append(randNum)
print 'Your random number generated and successfully stored.'
print storeRand
else:
157
print 'There is already the same number in the directory, run function again to store a different
number.'
print 'Generating an integer between the range ', start, 'to ', stop, 'with step value ', step, '...'
print randNum
else:
print 'There is already the same number in the directory, run function again to store a different
number.'
#showing usage of choice(). If a non empty sequence is given, then this function just chooses an
element from that sequence and return it to you.
readSeq = choice(seq)
else:
print 'There is already the same number in the directory, run function again to store a different
number.'
ch = 'Y'
158
while ch == 'Y':
print
print 'Enter 1 to generate a random number between 0 and 1 and store it in a directory.'
print 'Enter 2 to generate a random integer between your specified range and store it in a directory.'
print 'Enter 3 to generate a random integer between your specified range with **STEP VALUE** and
store it in a directory.'
print 'Enter 4 to generate a random choice for your sequence.'
try:
random_random()
elif x == 2:
random_randint(ul, ll)
elif x == 3:
elif x == 4:
random_choice(seq)
else:
print 'Invalid choice!!!'
except:
159
Output
160
161