Você está na página 1de 162

computer science

SUBMITTED TO: Submitted by:

MS. MEENA DOGRA Viplove Mittal


ACKNOWLEDGEMENT

I take this opportunity to express my profound gratitude


and deep regards to my guide Ms. Meena Dogra for her
exemplary guidance, monitoring and constant
encouragement throughout the course of this project.
The blessing and help given by her shall carry me a long
way in the journey of life on which I am about to embark.
I would also like to thank my classmates for their
cooperation during the period of my assignment.
Lastly, I thank almighty and my parents for their constant
encouragement without which this assignment would
not be possible.

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.

Some of the features of python are:-

 It is general purpose programming language which can be used for


both scientific and non-scientific programming.
 It is platform independent programming language.
 It is very simple high level language with vast library of add-on
module.
 It is excellent for beginners as it gives immediate results.
 The programs written in python are easily readable and
understandable.
 It is easy to learn and use.

3
CLASSES &
OBJECTS

4
Question 1:
Create a class TOURIST in python having following specifications:

Instance attributes:
cno - to store cab no.

ctype - to store a character ‘A’,’B’,’C’ as city type

perkm - to store per km charges

distance - to store the distance travelled in kms

Methods:
init() - to assign initial values of ctype as ‘A’ and cno. As ‘0000’

citycharges() -to assign perkm as per the following conditions:

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.cno=input("enter cab no.:")

self.ctype=raw_input("enter city type [A/B/C]:")

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

print "cab no. is",self.cno

print "city type is",self.ctype

print "charges per km are",self.perkm

print "total amount is",self.perkm*self.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

print "object inialized"

def input(self):

self.rno=input("enter roll no.:")

self.name=raw_input("enter name:")

self.marks=input("enter marks:")

def output(self):

print "roll no.of the student is",self.rno

print "name of the student is",self.name

print "marks of the student are",self.marks

@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.rno=input("enter roll no.:")

self.name=raw_input("enter name:")

self.__marks=input("enter marks:")

def output(self):

print "roll no.of the student is",self.rno

print "name of the student is",self.name

print "marks of the student are",self.__marks

s1=Student()

print s1.__dict__#returns a dictionary containing the namespace of the

class

print Student.__name__#returns the name of the class

print s1.__class__.__name__#returns the name of the 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

print Student.__doc__#returns the doc string of the class if defined otherwise


returns none

print Student.__bases__#returns the base class of the class

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

print "object created"

def show(self):

print self.name

print self.sal

print "object printed"

e1=emp("amit",25000) #init called

e2=emp("anant",30000) #init called

print hasattr(e1,"sal")

print hasattr(e1,"salary")

print e1.name

setattr(e1,"name","amit jain")

print e1.name

#if an attribute does not exist,then it will be created

setattr(e1,"desig","manager") # creates desig attribute for e1

print e1.desig

print getattr(e1,"sal")

#print getattr(e1,"salary") AttributeError is reported

19
delattr(e1,"sal")

#delattr(e1,"salary") AttributeError is reported

print hasattr(e1,"sal")

Output

20
INHERITANCE

21
#Single Inheritance
class Person:

def __init__(self,n,a):

self.name=n

self.age=a

print "init of person called"

class Employee(Person):

def __init__(self,n,a,sal):

Person.__init__(self,n,a)

self.salary=sal

print "init of Employee called"

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

print "in init of A"

class B:

def __init__(self,y):

self.b=y

print "in init of B"

class C(A,B):

def __init__(self,x,y,z):

A.__init__(self,x)

B.__init__(self,y)

self.c=z

print "in init of C"

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

self.category=raw_input("Enter medicine category: ")

self.mfg=raw_input("Enter date of manufacture: ")

self.cmp=raw_input("Enter company name: ")

def show(self):

print "Medicine category: ",self.category

print "Date of manufacture: ",self.mfg

print "Company name: ",self.cmp

class Capsules(Medicine):

def __init__(self):

Medicine.__init__(self)

self.Capsule_name=" "

self.Volume_label=" "

def Inp(self):

print "Capsule:"

self.inp()

self.Capsule_name=raw_input("Enter capsule name: ")


26
self.Volume_label=raw_input("Enter volume label: ")

def Output(self):

print "Capsule:"

self.show()

print "Capsule_name: ",self.Capsule_name

print "Volume_label: ",self.Volume_label

class Antibiotic(Capsules):

def __init__(self):

Capsules.__init__(self)

self.Dosage_units=0

self.side_effects=" "

def Input(self):

print "Antibiotic:"

self.Inp()

self.Dosage_units=input("Enter dosage units: ")

self.side_effects=raw_input("Enter side effects: ")

def output(self):

print "Antibiotic:"

self.Output()

print "Dosage units: ",self.Dosage_units

print "Side effects: ",self.side_effects

a1=Antibiotic()

a1.Input()

27
a1.output()

output

28
#Hierarchical Inheritance
class person:

def __init__(self,n,a):

self.name=n

self.age=a

print "init of person called"

class employee(person):

def __init__(self,n,a,sal):

person.__init__(self,n,a)

self.salary=sal

print "init of employee called"

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

print "init of student called"

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

self.name=raw_input("Enter name: ")

self.c_no=input("Enter contact number: ")

def show(self):

print "Name: ",self.name

print "Contact number: ",self.c_no

class Teacher(Person):

def __init__(self):

Person.__init__(self)

self.t_id=0

def Inp(self):

print "Teacher:"

self.t_id=input("Enter teacher id: ")

self.inp()

def Output(self):

print "Teacher:"

print "Teacher id: ",self.t_id

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.r_no=input("Enter roll number: ")

self.a_no=input("Enter admission number: ")

self.inp()

self.mks=input("Enter marks: ")

def out(self):

print "Student:"

print "Roll number: ",self.r_no

print "Admission number: ",self.a_no

self.show()

print "Marks: ",self.mks

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.s_id=input("Enter school id: ")

self.s_name=raw_input("Enter school name: ")

self.Inp()

self.Input()

def Show(self):

print "School id: ",self.s_id

print "School name: ",self.s_name

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

print "Furniture object initialised"

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

print "Sofa object initialised"

def getseats(self):

return self.nos

def getcost(self):
35
print "Cost:"

return self.cost

def show(self):

furniture.show(self)

print "No. of seats=",self.nos

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

print "Trainer object initialised"

def getname(self):

print "Trainer name:",

return self.name

def gettid(self):

print "Trainer id:",

return self.tid

class learner:

def __init__(self,n1,lid):

self.lid=lid

self.lname=n1

print "Learner object initialised"

def getlname(self):

print "Learner name:",

return self.lname

def getlid(self):

print "Learner id:",

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

print "Institute object initialised"

def getiname(self):

print "Institute name:",

return self.iname

def geticode(self):

print "Institute code:",

return self.icode

i1=institute("Trainer 1","T01","Learner 1","L01","Abc","I01")

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=""

def getdata (self):

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)

self.salary=input("enter the salary")

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)

self.nod=input("enter no leave days")

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

self.name=raw_input("Enter name: ")

self.c_no=input("Enter contact number: ")

def show(self):

print "Name: ",self.name

print "Contact number: ",self.c_no

class Student(Person):

def __init__(self):

Person.__init__(self)

self.r_no=0

self.mks=0

def inp(self):

print "Student:"

Person.inp(self)

self.r_no=input("Enter roll number: ")

self.mks=input("Enter marks: ")

def show(self):
44
Person.show(self)

print "Roll number: ",self.r_no

print "Marks: ",self.mks

s1=Student()

s1.inp()

s1.show()

p1=Person()

p1.inp()

p1.show()

45
Output

46
LINEAR
LIST

47
#Linear Search
l=[]

n=input("Enter how many elements in the list:")

for i in range(0,n):

val=input("Enter value for the list at index:"+str(i)+":")

l.append(val)

l.sort()

key=input("Enter the value to be searched:")

f=0

if key>l[len(l)-1]:

print "Value not present in the list."

for j in l:

if j==key:

pos=l.index(j)+1

print "Key found at positon.",pos

break

elif j>key:

print "Value greater than key found."

break

48
output

49
#Binary Search
l=[]

n=input("Enter how many elements in the list:")

for i in range(0,n):

val=input("Enter value for the list at index"+" "+str(i))

l.append(val)

l.sort()

item=input("Enter the element to be searched:")

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

elif item < l[mid]:

ub=mid-1

else:

return -1

ind=bsearch(l,item)

if ind==-1:
50
print "Value not present in the list:"

else:

print "Value found at position",ind+1,"."

Output

51
#Bubble Sort
l=[]

n=input("Enter how many elements in the list:")

for j in range(0,n):

val=input("Enter value for the list: ")

l.append(val)

print "Unsorted List:",l

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

print "Sorted list:",l

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=[]

n=input("Enter no. of many elements in the list:")

for j in range(0,n):

val=input("Enter value for the list:")

l.append(val)

print "Unsorted list:",l

selsort(l)

print "Sorted list:",l

54
output

55
#Insertion Sort
def insertionsort(l):

for i in range(1,len(l)):

v=l[i]

j=i

while j>=1 and l[j-1]>v:

l[j]=l[j-1]

j-=1

l[j]=v

l=[]

n=input("Enter how many elements in the list:")

for j in range(0,n):

val=input("Enter value for the list:")

l.append(val)

print "Unsorted lst:",l

insertionsort(l)

print "Sorted list:",l

56
output

57
#Insertion using bisect module
import bisect

l=[1,3,5,12,29,36,50]

print "The list in sorted order is:"

print l

item=input("Enter the itemto be inserted in the list:")

ind=bisect.bisect(l,item)

bisect.insort(l,item)

print item,"inserted at index",ind

print l

output

58
#Deletion using Bisect Module
import bisect

l=[2,8,22,35,43,50]

print "The list in sorted order is:"

print l

item=input("Enter the item to be deleted from the list:")

ind=bisect.bisect(l,item)

del l[ind-1]

print item,"deleted from index",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)

print "Value added to queue."

def deleteq():

if len(q)==0:

print "Queue is empty."

else:

print "Value removed is ",q.pop(0),"."

def showq():

if len(q)==0:

print "Queue is empty."

else:

for i in range(0,len(q)):

print q[i]

ans="y"

while ans=="y" or ans=="Y":


61
print "1.ADD TO QUEUE"

print "2.DELETE FROM QUEUE"

print "3.DISPLAY QUEUE"

ch=input("Enter your choice:")

if ch==1:

addqueue()

elif ch==2:

deleteq()

elif ch==3:

showq()

else:

print "Invalid choice."

ans=raw_input("Do you wish to continue[y/n]?")

62
output

63
#Program to implement queue using class
class queue:

q=[]

def addqueue(self):

a=input("Enter a value:")

queue.q.append(a)

print "Value added to queue."

def deleteq(self):

if len(queue.q)==0:

print "Queue is empty."

else:

print "Value removed is ",queue.q.pop(0),"."

def showq(self

):

if len(queue.q)==0:

print "Queue is empty."

else:

for i in range(0,len(queue.q)):

print queue.q[i]

ans="y"
64
q1=queue()

while ans=="y" or ans=="Y":

print "1.ADD TO QUEUE"

print "2.DELETE FROM QUEUE"

print "3.DISPLAY QUEUE"

ch=input("enter your choice:")

if ch==1:

q1.addqueue()

elif ch==2:

q1.deleteq()

elif ch==3:

q1.showq()

else:

print "Invalid choice."

ans=raw_input("Do you wish to continue[y/n]?")

65
output

66
# Program to implement stack using list without class
s=[]

def push():

a=input("Enter a value:")

s.append(a)

print "Value pushed to stack."

def pop():

if len(s)==0:

print "Stack is empty."

else:

print "Value removed is ",s.pop(),"."

def show():

if len(s)==0:

print "Stack is empty."

else:

for i in range(len(s)-1,-1,-1):

print s[i]

ans="y"

while ans=="y" or ans=="Y":

print "----STACK OPERATIONS----"

print "1.PUSH"
67
print "2.POP"

print "3.DISPLAY"

ch=input("Enter your choice:")

if ch==1:

push()

elif ch==2:

pop()

elif ch==3:

show()

else:

print "Invalid choice."

ans=raw_input("Do you wish to continue[y/n]?")

68
output

69
#Program to implement stack using class
class stack:

s=[] #class attribute

def push(self,n):

stack.s.append(n)

print "Value added to stack."

def pop(self):

if len(stack.s)==0:

print "Stack is empty."

else:

print "Value removed is ",stack.s.pop(),"."

def show(self):

if len(stack.s)==0:

print "Stack is empty."

else:

for i in range(len(stack.s)-1,-1,-1):

print stack.s[i]

s1=stack()

ans="y"

while ans=="y" or ans=="Y":

print "------STACK OPERATIONS------"

print "1.PUSH"

print "2.POP"
70
print "3.DISPLAY"

ch=input("Enter your choice:")

if ch==1:

a=input("Enter the value to be added to stack:")

s1.push(a)

elif ch==2:

s1.pop()

elif ch==3:

s1.show()

else:

print "Invalid choice."

ans=raw_input("Do you wish to continue[y/n]?")

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

print "Number of vowels:",vc

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

print "Number of '#' :",vc

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

print "Number of 'a':",va

print "Number of 'b':",vb

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

print "Number of lines:" ,len(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

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)

print "data appended"

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

print "Count for His:",c1

print "Count for Her:”,c2

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

s1="The cat is the Tom\n" + "And the mouse is the Jerry\n"

fw.write(s1)

print "data appended"

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

s1="Ee aaa A ii II ou OU\n"

fw.write(s1)

print "data appended"

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

print "Program executed."

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

s=raw_input("Enter the line:")

l.append(s+'\n')

fw.writelines(l)

print "text written to file"

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

s=raw_input("Enter the line:")

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

print "object created"

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

self.sal=input("enter the new sal:")

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

n=input("enter the eno to be searched:")

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:

print "no record found"

#------------------------------------------------------------------------------------------------
------------------

def showename():

fr=open("empb.dat","rb")

n=raw_input("enter the ename to be searched:")

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

print "no record found"

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

print f,"matching records found"

#------------------------------------------------------------------------------------------------
------------------

def delete():

fr=open("empb.dat","rb") #master file

fw=open("temp.dat","wb") #transaction or temporary file

n=input("enter the eno to be deleted:")

f=0

try:

while True:

e1=pickle.load(fr)
95
if e1.eno==n:

print "record to be deleted found..."

print "record will be deleted from file.."

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:

print "no record found"

else:

print "file now contains-"

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:

print "record to be modified found..."

print "edit the record"

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:

print "no record found"

else:

print "file now contains-"

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:

print "no record found"

else:

print f,"records copied.."

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:

print "no record found"

99
else:

print f,"records transferred.."

showall("highsal1.dat")

print "-------------------------------------------------------------------------"

showall("empb.dat")

#------------------------------------------------------------------------------------------------
------------------

print """User operation menu:

1.Type append() to add a new record:

2.Type showall(filename) to view a file:

3.Type showen() to view a record using eno.

4.Type showename() to view a record using ename.

5.Type showsal() to view salaries(>15000).

6.Type delete() to remove a record.

7.Type update() to edit a record.

8.Type copy() to copy records (sal>15000).

9.Type transfer() to transfer records (sal>15000) in another file."""

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

print "Files joined."

Output

104
#Program to tell pointer index
fr=open("1.txt","r")

print "File opened at position:",fr.tell()

print fr.read()

fr.seek(6,0)

print fr.read()

print "pointer at position",fr.tell()

fr.close()

Output

105
#Program to remove a word from file
import os

fr=open("1.txt","r") #Master file

fw=open("10.txt","w") #Transaction file

s=fr.read()

l=s.split()

n=raw_input("Enter the word to be removed:")

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

print "Word removed."

106
Output

107
#Creating a dictionary and storing it in binary file
import pickle

fw=open("d1.dat","wb")

n=input("how many records:")

for i in range(n):

d={}

k=input("enter key:")

v=raw_input("enter value for 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={}

n=input("How many records:")

for i in range(n):

k=input("Enter rollno:")

l=raw_input("Enter value for name,class,sec in square brackets:")

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={}

n=input("Enter the position at which u want to insert:")

f=0

count=1

d1={}

try:

while True:

if count<>n:

d1=pickle.load(fr)

pickle.dump(d1,fw)

#print "old value copied",count

else:

k=raw_input("enter key:")

v=input("enter value for key:")

d[k]=v

pickle.dump(d,fw)

f+=1

print "new value copied",count


112
count+=1

except EOFError:

fr.close()

fw.close()

os.remove("d1.dat")

os.rename("temp.dat","d1.dat")

if f==0:

print "invalid position"

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

print "EMP NO",self.eno

print "EMP NAME",self.ename

try:

e1=emp()

print e1.name

e1.output()

except AttributeError:

print "Attribute 'name' does not exist."

else:

print "no error"

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:

print "attribute 'outputt' does not exist"

else:

print "no error"

118
Output

119
#Program to handle division by zero exception
try:

dividend=input("Enter the dividend:")

divisor=input("Enter the divisor:")

ans=dividend/divisor

except ZeroDivisionError:

print "divisor cannot be zero"

else:

print "ans=",ans

print "out of try....."

Output

120
#Import Error
try:

base=input("Enter the base:")

e=input("Enter the exponent:")

from math import power

p=pow(base,e)

except ImportError:

print "invalid module name"

else:

print "ans=",p

print "out of try....."

Output

121
#Index Error
try:

s=raw_input("Enter a string of length less than 9:")

print s[1]

print s[9]

except IndexError:

print "invalid value for string index"

else:

print "string=",s

finally:

print "finally always executes"

Output

122
#Key Error
d=dict()

try:

for i in range(5):

k=input("Enter the key:")

v=raw_input("enter the value for key")

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:

print "invalid value for key"

except: #will match all other exceptions

print "error in program"

finally:

print "finally always executes"

123
Output

124
#Program to handle division by zero exception by
explicitly raising it
try:

dividend=input("Enter the dividend:")

divisor=input("Enter the divisor:")

if divisor==0:

raise ZeroDivisionError

ans=dividend/divisor

print ans

except ZeroDivisionError:

print "divisor cannot be zero"

else:

print "ans=",ans

print "out of try....."

125
Output

126
#Program to handle division by zero exception by
explicitly raising it with a user defined message
try:

dividend=input("Enter the dividend:")

divisor=input("Enter the divisor:")

if divisor==0:

raise ZeroDivisionError,str(dividend)+"/0 not possible"

#raise ZeroDivisionError(str(dividend)+"/0 not possible")

ans=dividend/divisor

except ZeroDivisionError,e:

print "exception:-",e

else:

print "ans=",ans

print "out of try....."

127
Output

128
#Program to handle type error exception
try:

n1=input("Enter the first value:")

n2=input("Enter the second value:")

sum=n1+n2

except TypeError:

print "invalid type of value for addition operation"

else:

print "sum=",sum

print "out of try....."

Output

129
#Program to create and raise user defined exception
class MyError(Exception): #'Exception' is the inbuilt base class

pass

err1=MyError("negative marking not allowed..") #init of base class is called

err2=MyError

try:

marks=input("Enter the marks:")

if marks<0:

raise err1 #'raise' can take object name or class name

elif marks>100:

raise err2,"maximum mark are 100.."

elif marks>40:

print "promoted to next class.."

else:

print "your re-examination is scheduled.."

except MyError,e: #'except' can take only class name or inbuilt error name

print "exception:-",e.message,"Marks entered:",marks

else:

print "Marks=",marks

finally:

print "finally always executes..."

print "out of try....."

130
Output

131
#Program to handle VALUE error exception
try:

n1=int(raw_input("Enter the first value:"))

n2=int(raw_input("Enter the second value:"))

sum=n1+n2

except ValueError:

print "invalid value for input operation"

else:

print "sum=",sum

print "out of try....."

Output

132
SQL

133
SQL QUERIES
Question 1:
Table : Students

Adno Name Average Sex Scode

501 R.Jain 98 M 111

545 Kavita 73 F 333

705 K.Rashika 85 F 111

754 Rahul Goel 60 M 444

892 Sahil Jain 78 M 333

935 Rohan Saini 85 M 222

955 Anjali 64 F 444

983 Sneha Aggarwal 80 F 222

Write queries based upon students table:

1) Give a command to create the above table students.


A) CREATE TABLE Students(Adno number(3) Primary Key, Name varchar2(20) not null,
Average number(2), Sex varchar2(5), Scode number(3));
2) Give a command to insert first row of the table.
A) INSERT into Students values(501,’R.Jain’,98,’M’,111);
3) Display all students‘ information.
A) SELECT * FROM Students;
4) Display Rohan Saini’s information.
A) SELECT * FROM Sudents WHERE Name =’Rohan Saini’;
134
5) Display number of students in the table.
A) SELECT count(*) FROM Students;
6) Display number of students in each sex.
A) SELECT Sex, count(*) FROM Students GROUP BY Sex;
7) Display students’ information in ascending order using name.
A) SELECT * FROM Students order by Name;
8) Display students’ information in descending order using average marks.
A) SELECT * FROM Students order by Average desc;
9) Display students’ name starting with letter ‘K’.
A) SELECT Name FROM Students WHERE Name like ‘K%’;

10)Display students’ information , whose name ends with “l”.


A) SELECT * FROM Students WHERE Name like ‘%l’;
11)Display a report with adno, name, average*5 as total marks from student table.
A) SELECT Adno, Name, Average*5 ‘Total marks’, FROM Students;
12)Display students’ information, whose average marks are in between 80 to 90.
A) SELECT * FROM Students WHERE Average between 80 and 90;
13)Display students’ information who are getting average marks of more than 80 and scode
333.
A) SELECT * FROM Students WHERE Average>80 and Scode=333;
14)Display students’ name and average marks, whose scode is 111,222 and 333.
A) SELECT Name, Average WHERE Scode in (111,222,333);
15) Display sum of average marks.
A) SELECT sum(Average) FROM Students;
16) Display maximum average marks.
A) SELECT max(Average) FROM Students;
17) Display minimum average marks.
A) SELECT min(Average) FROM Students;
18) Display average value of average marks.
A) SELECT avg(Average) FROM Students;
19) Display maximum, minimum and sum of average marks in each scode.
A) SELECT Scode, max(Average), min(Average), sum(Average) GROUP BY Scode;
20) Display number of students in each scode.
A) SELECT Scode, count(*) FROM Students GROUP BY Scode;

135
Question 2:
Table : ACTIVITY

Acode Activity name Stadium ParticipantNum PrizeMoney ScheduleDate

1001 Relay 100X4 Star Annex 16 10000 23-Jan-2004

1002 High Jump Star Annex 10 12000 12-Dec-2003

1003 Shot Put Super Power 12 8000 14-Feb-2004

1005 Long Jump Star Annex 12 9000 01-Jan-2004

1008 Discuss Throw Super Power 10 15000 19-Mar-2004

Table : COACH

Pcode Name Acode

1 Ahmed Hussain 1001

2 Ravinder 1008

3 Janila 1001

4 Naaz 1003

Write the following queries:


1) Display the names of all activities with their Acode in descending order.
A) SELECT Acode, ActivityName FROM Activity order by Acode desc;
2) Display the sum of prize money for activities played for each of the stadim separately.
A) SELECT Stadium,sum(PrizeMoney) FROM Activity group by Stadium;
3) To display the Coach name and Acode in ascending order of Acode from table COACH.
A) SELCT Name,Acode FROM COACH ORDER by Acode;
136
4) Increase no of participants for Acode=1003 by 10;
A) UPDATE ACTIVITY set ParticipantsNum=ParticipantsNum +10 WHERE Acde=1003;
5) Increase prize money for all activities by 1000.
A) UPDATE ACTIVITY set PrizeMoney=PrizeMoney+1000;
6) Display details of all activities whose Scheduled date is earlier than 01-jan-2004 in
ascending order of no of participants.
A) SELECT * FROM ACITIVITY WHERE ScheduleDate<’01-Jan-2004’ ORDER by ParticipantsNum;
7) Display no of participants for each activity.
A) SELECT Acode,count(*) FROM ACTIVITY GROUP by Acode;
8) Display Acode,Aname and coach name for all activities.
A) SELECT A.Acode,ActivityName,Name FROM ACTIVITY A,COACH C WHERE A.Acode=C.Acode;
9) Display the number of rows in table coach.
A) SELECT count(*) FROM COACH;
10)Display names of all coaches that begin with R.
A) SELECT Name FROM COACH WHERE Name like ‘R%’;
11)Delete the record of activity of long jump.
A) Delete FROM ACTIVITY WHERE Activityname=’Long Jump’;

137
1. CREATE TABLE COMMAND

SQL> CREATE TABLE COMPANY

(EMPNO number (4) NOT NULL PRIMARY KEY, -- Assigning primary key

ENAME varchar (20) NOT NULL,

GENDER varchar (6),

JOB varchar (15),

HRDATE date,

SAL number (5),

DEPTNO number (2) ) ;

OUTPUT:

Table created

2. INSERT COMMAND

SQL> INSERT INTO COMPANY

(EMPNO, ENAME, GENDER, JOB, HRDATE, SAL, DEPTNO)

VALUES

(101, ‘ALEXIS’,’MALE’,’CEO’,’12-Nov-1998’, 95000,10) ;

OUTPUT:

COMPANY

EMPNO ENAME GENDER JOB HRDATE SAL DEPTNO

__________ __________ ______ __________ __________ _____ ____


101 ALEXIS MALE CEO 12-Nov-1988 95000 10

3. INSERT MULTIPLE RECORDS

SQL> INSERT INTO COMPANY


138
VALUES

(‘&EMPNO’, ‘&ENAME’ , ‘&GENDER’ , ‘&JOB’, ‘&HRDATE’ , ‘&SAL’ , ‘&DEPTNO’) ;

OUTPUT:

EMPNO ENAME GENDER JOB HRDATE SAL DEPTNO

__________ __________ ______ __________ __________ _____ ____


101 ALEXIS MALE CEO 12-Nov-1988 95000 10

102 RACHEL FEMALE MANAGER 19-Feb-1988 75000 20

103 ROSS MALE SALESMAN 2-Apr-1990 20000 30

104 MATT MALE SALESMAN 25-Aug-1989 20000 30

105 MONICA FEMALE ANALYST 7-Oct-1992 55000 40

106 PHOEBE FEMALE SALESMAN 20-Mar-1994 20000 30

107 CHANDLER MALE ANALYST 1- Jan- 1988 55000 40

4. CREATE TABLE FROM EXISITING TABLE

SQL> CREATE TABLE EMPLOY

AS

( SELECT EMPNO , ENAME , SAL

FROM COMPANY ) ;

OUTPUT:

EMPLOY

EMPNO ENAME SAL

__________ __________ ____


101 ALEXIS 95000

102 RACHEL 75000

103 ROSS 20000

104 MATT 20000


139
105 MONICA 55000

106 PHOEBE 20000

107 CHANDLER 55000

5. ASSIGNING FOREIGN KEY

SQL> CREATE TABLE EMPL

( EMPNO number (4) PRIMARY KEY ,

DEPTNO number (2) ,

DEPTCOMM number(4) ,

references COMPANY(EMPNO) ) ;

OUTPUT (AFTER INSERTING VALUES) :

EMPL

EMPNO DEPTNO DEPTCOMM

__________ _____ _______

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

EMPNO ENAME GENDER JOB HRDATE SAL DEPTNO


140
__________ __________ ______ __________ __________ _____ ____
101 ALEXIS MALE CEO 12-Nov-1988 95000 10

102 RACHEL FEMALE MANAGER 19-Feb-1988 75000 20

103 ROSS MALE SALESMAN 2-Apr-1990 20000 30

104 MATT MALE SALESMAN 25-Aug-1989 20000 30

105 MONICA FEMALE ANALYST 7-Oct-1992 55000 40

106 PHOEBE FEMALE SALESMAN 20-Mar-1994 20000 30

107 CHANDLER MALE ANALYST 1- Jan- 1988 55000 40

6. JOIN

SQL> SELECT EMPNO,ENAME , SAL , DEPTCOMM

FROM COMPANY, EMPL

WHERE COMPANY.EMPNO=EMPL.EMPNO

EMPNO ENAME SAL DEPTCOMM

__________ __________ ____ _______

101 ALEXIS 95000 4000

102 RACHEL 75000 2000

103 ROSS 20000 1500

104 MATT 20000 1500

105 MONICA 55000 1000

106 PHOEBE 20000 1500

107 CHANDLER 55000 1000

7. SELECT WITH COLUMN ALIAS

SQL> SELECT SAL*12 “ANNUAL SALARY”

FROM COMPANY ;

OUTPUT:
141
ANNUAL SALARY

1140000

900000

240000

240000

660000

240000

660000

8. MAX , MIN , AVG

SQL> SELECT MAX(SAL) , MIN(SAL) , AVG(SAL)

FROM COMPANY ;

OUTPUT:

95000

20000

48971

9. GROUPING

SQL> SELECT SAL

FROM COMPANY

GROUP BY JOB ;

OUTPUT:

JOB SAL

________ ____

CEO 95000

MANAGER 75000

SALESMAN 20000

ANALYST 55000

10. NUMBER OF EMPLOYEES


142
SQL> SELECT COUNT(EMPNO)

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)

SQL> SELECT JOB , SAL

FROM COMPANY

WHERE JOB NOT LIKE ‘A%’

GROUP BY JOB

HAVING AVG(SAL) > 50000

ORDER BY JOB DESC ;

OUTPUT:

JOB SAL

______ _____

CEO 95000

MANAGER 75000

12. USING BETWEEN

SQL> SELECT EMPNO

FROM COMPANY

WHERE SAL BETWEEN 50000 AND 90000 ;

OUTPUT:

EMPNO

_____
143
102

105

107

13. UPDATE COMMAND

SQL> UPDATE COMPANY

SET SAL = SAL+1000 ;

SQL> SELECT SAL

FROM COMPANY ;

OUTPUT:

SAL

____

96000

76000

21000

21000

56000

21000

56000

14. UPDATE COMMAND USING WHERE CONDITION

SQL> UPDATE COMPANY

SET SAL = SAL+1000

WHERE SAL=20000 ;

SQL> SELECT SAL

FROM COMPANY ;

OUTPUT:

SAL

____

95000
144
75000

21000

21000

55000

21000

55000

15. ALTER COMMAND

SQL> ALTER TABLE COMPANY

ADD (AGE number(2) ) ;

SQL> SELECT *

FROM COMPANY ;

OUTPUT:

EMPN0 ENAME GENDER JOB HRDATE SAL DEPTNO AGE

___ ________ ______ _________ __________ _____ ____ ____

101 ALEXIS MALE CEO 12-Nov-1988 95000 10 27

102 RACHEL FEMALE MANAGER 19-Feb-1988 75000 20 27

103 ROSS MALE SALESMAN 2-Apr-1990 20000 30 25

104 MATT MALE SALESMAN 25-Aug-1989 20000 30 26

105 MONICA FEMALE ANALYST 7-Oct-1992 55000 40 23

106 PHOEBE FEMALE SALESMAN 20-Mar-1994 20000 30 22

107 CHANDLER MALE ANALYST 1- Jan- 1988 55000 40 28

16. ALTER TO MODIFY EXISTING TABLE

SQL> ALTER TABLE COMPANY

MODIFY ( JOB char(20) ) ;

145
SQL> SELECT *

FROM COMPANY ;

OUTPUT:

EMPNO ENAME GENDER JOB HRDATE SAL DEPTNO

__________ __________ ______ __________ __________ _____ ____


101 ALEXIS MALE CEO 12-Nov-1988 95000 10

102 RACHEL FEMALE MANAGER 19-Feb-1988 75000 20

103 ROSS MALE SALESMAN 2-Apr-1990 20000 30

104 MATT MALE SALESMAN 25-Aug-1989 20000 30

105 MONICA FEMALE ANALYST 7-Oct-1992 55000 40

106 PHOEBE FEMALE SALESMAN 20-Mar-1994 20000 30

107 CHANDLER MALE ANALYST 1- Jan- 1988 55000 40

17. DELETE COMMAND TO DELETE ENTIRE TABLE

SQL> DELETE FROM COMPANY ;

18. DELETE COMMAND TO DELETE SPECIFIC ROWS

SQL> DELETE FROM COMPANY

WHERE SAL < 50000 ;

SQL> SELECT *

FROM COMPANY ;

OUTPUT:

EMPNO ENAME GENDER JOB HRDATE SAL DEPTNO


146
__________ __________ ______ __________ __________ _____ ____
101 ALEXIS MALE CEO 12-Nov-1988 95000 10

102 RACHEL FEMALE MANAGER 19-Feb-1988 75000 20

105 MONICA FEMALE ANALYST 7-Oct-1992 55000 40

107 CHANDLER MALE ANALYST 1- Jan- 1988 55000 40

19. DROP COMMAND

SQL> DELETE COMPANY ;

SQL> DROP COMPANY ;

OUTPUT:

Table dropped

20 . CREATE VIEW

SQL> CREATE VEIW V1 AS

SELECT *

FROM EMP ;

OUTPUT:

View created

21. DISPLAY VIEW V1

SQL> SELECT *

FROM V1 ;

147
OUTPUT:

EMPNO ENAME GENDER JOB HRDATE SAL DEPTNO

__________ __________ ______ __________ __________ _____ ____


101 ALEXIS MALE CEO 12-Nov-1988 95000 10

102 RACHEL FEMALE MANAGER 19-Feb-1988 75000 20

103 ROSS MALE SALESMAN 2-Apr-1990 20000 30

104 MATT MALE SALESMAN 25-Aug-1989 20000 30

105 MONICA FEMALE ANALYST 7-Oct-1992 55000 40

106 PHOEBE FEMALE SALESMAN 20-Mar-1994 20000 30

107 CHANDLER MALE ANALYST 1- Jan- 1988 55000 40

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 ###'

#first of all importing random module.

from random import*

storeRand = []

#showing the usage of random.random()

def random_random():

randNum = random()

print 'Generating a random number...'


print randNum
if randNum not in storeRand:

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 'Your random number generated and successfully stored.'

#showing usage of randint()

def random_randint(up = 10, low = 0):

randNum = randint(low, up)

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.'

#showing usage of randrange()

def random_randrange(start = 0, stop = 100, step = 5):

randNum = randrange(start, stop, step)

print 'Generating an integer between the range ', start, 'to ', stop, 'with step value ', step, '...'
print randNum

if randNum not in storeRand:


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.'

#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.

def random_choice(seq = 'abcd'):

readSeq = choice(seq)

print 'Choosing an element from the given sequence...'


print readSeq

if readSeq not in storeRand:


storeRand.append(readSeq)
print 'Your random choice 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.'

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:

x = input('Enter your choice: ')


if x == 1:

random_random()

elif x == 2:

ll = input('Enter lower limit: ')


ul = input('Enter upper limit: ')

random_randint(ul, ll)

elif x == 3:

ll = input('Enter lower limit: ')


ul = input('Enter upper limit: ')
step = input('Enter the step value: ')

random_randrange(ll, ul, step)

elif x == 4:

seq = raw_input('Enter your seqence: ')

random_choice(seq)

else:
print 'Invalid choice!!!'

except:

print 'An Error has occured!'

ch = raw_input('Do you want to continue? ').upper()

159
Output

160
161

Você também pode gostar