Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 36

PROGRAM 1

'''Program that reads a text file that is identical except that every blank
space is replaced by hyphen '-' '''

s="India is great"
f=open("abc.txt","w")
f.write(s)
f.close()
f=open("abc.txt","r")
t=f.read()
print("original contents are:",t)
g=open("data.txt","w")
for i in t:
if(i==" "):
g.write("-")
else:
g.write(i)
g.close()
f.close()
g=open("data.txt","r")
print("replaced contents are:",g.read())
g.close()

OUTPUT:
original contents are: India is great
replaced contents are: India-is-great
PROGRAM 2

'''Program to count and display the number of lines starting with alphabet
'A' or 'a' present in a text file "lines.txt" '''

s=["India is my country\n","All indians are my brothers and sisters\n""and


i am proud to be an indian\n"]
f=open("data.txt","w")
f.writelines(s)
f.close()
f=open("data.txt","r")
t=f.readlines()
count=0
for i in t:
if(i[0]=="A" or i[0]=="a"):
print(i)
count+=1
f.close()
print("number of lines starting with A or a is",count)

OUTPUT:
All indians are my brothers and sisters

and i am proud to be an indian

number of lines starting with A or a is 2


PROGRAM 3

'''Program to get roll number,name and marks of the student of class(get


from user) and store these in a file called "marks.dat" '''
f=open("marks.dat","w")
n=int(input("enter number of students:"))
f.write("Rollno."+"\t"+"Name"+"\t"+"eng"+"\t"+"Hindi"+"\t"+"Math"+
"\n")
for i in range(n):
print("Enter information of student",i+1)
rno=int(input("enter roll number:"))
name=input("enter name:")
eng=float(input("enter english marks:"))
hindi=float(input("enter hindi marks:"))
maths=float(input("enter maths marks:"))

f.write(str(rno)+"\t"+name+"\t"+str(eng)+"\t"+str(hindi)+"\t"+str(maths)+
"\n")
f.close()
print("student's information are:")
f=open("marks.dat","r")
print(f.read())
f.close()
OUTPUT:
enter number of students:2
Enter information of student 1
enter roll number:1
enter name:AJAY
enter english marks:56
enter hindi marks:55
enter maths marks:89

Enter information of student 2


enter roll number:2
enter name:ANJALI
enter english marks:78
enter hindi marks:65
enter maths marks:98
student's information are:
Rollno. Name eng Hindi Math
1 AJAY 56.0 55.0 89.0
2 ANJALI 78.0 65.0 98.0
PROGRAM 4
'''Program to perform read and write operations on binary file'''

import pickle
s="india is great"
f=open("abc.bin","wb")
pickle.dump(s,f)
f.close()
f=open("abc.bin","rb")
t=pickle.load(f)
print("file contents are:",t)
f.close()

OUTPUT:
file contents are: india is great
PROGRAM 5

'''Program to find factorial of a number recursively'''

def factorial(n):
if(n==1):
return 1
else:
return(n*factorial(n-1))
n=int(input("enter a number whose factorial you want to find"))
b=factorial(n)
print("factorial of",n,"is",b)

OUTPUT:
enter a number whose factorial you want to find 5
factorial of 5 is 120
PROGRAM 6

'''Program to print fibonacci series recursively'''

def fib(n):
if(n==1):
return 0
elif(n==2):
return 1
else:
return(fib(n-1)+fib(n-2))
#-main-
n=int(input("enter no. of terms required:"))
for i in range(1,n+1):
print(fib(i),end=',')
print("...")

OUTPUT:
enter no. of terms required:7
0,1,1,2,3,5,8,...
PROGRAM 7

'''Program to perform binary search on linear list recursively'''

def bsearch(arr,n,beg,last):
if(beg>last):
return -1
mid=int((beg+last)/2)
if(arr[mid]==n):
return mid
elif(arr[mid]>n):
last=mid-1
else:
beg=mid+1
return bsearch(arr,n,beg,last)
#_main_
l=eval(input("enter list elements in ascending order:"))
n=int(input("enter number you want to search"))
last=len(l)-1
beg=0
t=bsearch(l,n,beg,last)
if(t<0):
print("element not found")
else:
print("element found at index",t)

OUTPUT:

enter list elements in ascending order:[1,2,3,4,5]

enter number you want to search2


element found at index 1
PROGRAM 8

'''Program that computes the sum of number 1.....n recursively,get the value
of last number from user'''

def sum(num):
if(num==1):
return 1
else:
return(num+sum(num-1))
#_main_
n=int(input("enter total numbers:"))
t=sum(n)
print("sum of numbers from", n,"to 1 is",t)

OUTPUT:

enter total numbers:5


sum of numbers from 5 to 1 is 15
PROGRAM 9

'''Program to sort a list either by bubble sort technique or insertion sort


technique based on the user's choice'''

def bsort(a):
t=len(a)
print("list before sorting",a)
for i in range(0,t):
for j in range(0,t-i-1):
if(a[j]>a[j+1]):
a[j],a[j+1]=a[j+1],a[j]
print("list after sorting is:",a)

def insertsort(a):
print("list before sorting",a)
for i in range(1,len(a)):
j=i-1
key=a[i]
while(j>=0 and key<a[j]):
a[j+1]=a[j]
j-=1
a[j+1]=key
print("list after sorting is",a)

n=eval(input("enter list elements:"))


print("1.Bubble Sort")
print("2.Insertion Sort")
print("3.Exit")
ch=int(input("enter choice(1 to 3):"))
if(ch==1):
bsort(n)
elif(ch==2):
insertsort(n)
elif(ch==3):
exit
else:
print("invalid choice")
OUTPUT:

enter list elements:[4,2,9,1,0,5,6,8]


1.Bubble Sort
2.Insertion Sort
3.Exit

enter choice(1 to 3):1


list before sorting [4, 2, 9, 1, 0, 5, 6, 8]
list after sorting is: [0, 1, 2, 4, 5, 6, 8, 9]
PROGRAM 10

'''Program to insert an item in a sorted list using bisect module'''

import bisect
n=eval(input("enter list elements in ascending order:"))
print("original list is:",n)
a=int(input(" enter number you want to insert:" ))
bisect.bisect(n,a)
bisect.insort(n,a)
print("list after insertion of new element is:",n)

OUTPUT:

enter list elements in ascending order:[1,3,4,5,6]


original list is: [1, 3, 4, 5, 6]

enter number you want to insert:2


list after insertion of new element is: [1, 2, 3, 4, 5, 6]
PROGRAM 11

'''Program to implement 2-D linear list'''

r=int(input("total number of rows:"))


row=[]
for i in range(r):
col=[]
c=int(input("total number of columns:"))
for j in range(c):
n=int(input("enter number"))
col.append(n)
row.append(col)
print("2-D list is:",row)

OUTPUT:
total number of rows:3

total number of columns:2


enter number1
enter number2

total number of columns:2


enter number3
enter number4

total number of columns:4


enter number5
enter number6
enter number7
enter number8

2-D list is: [[1, 2], [3, 4], [5, 6, 7, 8]]


PROGRAM 12

'''Program to delete an item from a sorted linear list'''


l=eval(input("enter elements in sorted list"))
n=int(input("enter number you want to delete"))
print("list before deletion of an element is:",l)
fl=0
for i in range(len(l)):
if(l[i]==n):
fl=1
break
if(fl==1):
del(l[i])
print("list after deletion of an element is:",l)
else:
print("element which you want to delete is not found in the list")

OUTPUT:
enter elements in sorted list[1,2,3,4,5]
enter number you want to delete:3
list before deletion of an element is: [1, 2, 3, 4, 5]
list after deletion of an element is: [1, 2, 4, 5]
PROGRAM 13

'''Menu driven program to perform insert or delete operation in a queue'''

def enqueue(l):
rear=len(l)
n=int(input("enter number you want to insert"))
if(rear<0):
front=0
l.append(n)
else:
rear+=1
l.append(n)
print("queue after insertion of an element is:",l)

def dequeue(l):

print("queue before deletion of an element is:",l)


if(l==[]):
print("underflow,queue is empty")

else:
front=0
del(l[front])
front+=1
print("queue after deletion of an element is:",l)

l=[]
c='y'
while(c=='y' or c=="Y"):
print("1.Enqueue operation")
print("2.Dequeue operation")
print("3.Exit")
ch=int(input("enter your choice(1-3):"))
if(ch==1):
enqueue(l)
elif(ch==2):
dequeue(l)
elif(ch==3):
break
else:
print("invalid choice:")
c=input("Do you want to perform more operations(y/n)")

OUTPUT:
1.Enqueue operation
2.Dequeue operation
3.Exit

enter your choice(1-3):1


enter number you want to insert1
queue after insertion of an element is: [1]

Do you want to perform more operations(y/n)Y


1.Enqueue operation
2.Dequeue operation
3.Exit

enter your choice(1-3):1


enter number you want to insert2
queue after insertion of an element is: [1, 2]

Do you want to perform more operations(y/n)Y


1.Enqueue operation
2.Dequeue operation
3.Exit

enter your choice(1-3):2


queue before deletion of an element is: [1, 2]
queue after deletion of an element is: [2]

enter your choice(1-3):2


queue before deletion of an element is: [2]
queue after deletion of an element is: []
PROGRAM 14

'''Program to perform push or pop operation in a stack based on user's


choice'''

def push(stack):
top=len(stack)
n=int(input("enter number you want to insert:"))
top+=1
stack.append(n)
print("stack after insertion of an element is:",stack)

def Pop(stack):
top=len(stack)-1
if(stack==[]):
print("underflow,stack is empty")
else:
del(stack[top])
top-=1
print("stack after deletion of an element is:",stack)

stack=[]
c="y"
while(c=="y" or c=="Y"):
print("1.Push operation")
print("2.pop operation")
print("3.exit")
ch=int(input("enter your choice(1 to 3):"))
if(ch==1):
push(stack)
elif(ch==2):
Pop(stack)
elif(ch==3):
break
else:
print("invalid choice")
c=input("Do you want to performmore operations(y/n):")
OUTPUT:
1.Push operation
2.pop operation
3.exit

enter your choice(1 to 3):1


enter number you want to insert:1
stack after insertion of an element is: [1]

Do you want to performmore operations(y/n):Y


1.Push operation
2.pop operation
3.exit

enter your choice(1 to 3):1


enter number you want to insert:3
stack after insertion of an element is: [1, 3]

Do you want to performmore operations(y/n):Y


1.Push operation
2.pop operation
3.exit

enter your choice(1 to 3):2


stack after deletion of an element is: [1]

Do you want to performmore operations(y/n):Y


1.Push operation
2.pop operation
3.exit

enter your choice(1 to 3):2


stack after deletion of an element is: []
Do you want to performmore operations(y/n):Y
1.Push operation
2.pop operation
3.exit

enter your choice(1 to 3):2


underflow,stack is empty
PROGRAM 15

'''Program to search an element in a list by linear search method'''

l=eval(input("enter list elements:"))


n=int(input("enter number you want to search:"))
fl=0
for i in range(len(l)):
if(l[i]==n):
fl=1
break
if(fl==1):
print("element found at index",i)
else:
print("element not found")

OUTPUT:

enter list elements:[2,4,6,8,10]

enter number you want to search:6


element found at index 2
PROGRAM 16

'''Program for tkinter based GUI application'''

import tkinter

def wquit():
print("Hello,getting out of there")

root=tkinter.Tk()
widget1=tkinter.Label(root,text="hello there")
widget1.pack()
widget2=tkinter.Button(root,text="OK",command=wquit)
widget2.pack()
widget3=tkinter.Button(root,text="CANCEL",command=root.quit)
widget3.pack()
root.mainloop()

OUTPUT:
Program 17

'''Program to plot the bar chart'''

import matplotlib.pyplot as plt


items=["Food","Clothing","Education","Misc.","Savings"]
Amount=[2100,600,1200,1500,1000]
plt.title("Items Expenditure")
plt.xlabel("items")
plt.ylabel("Amount(in Rs.)")
plt.bar(items,Amount,width=0.50,color=["red","green","blue","yellow","p
urple"])
plt.show()

OUTPUT:
PROGRAM 18

'''Program to count the number of words in a text file "quotes.txt" '''

s=["india is my country.\n","all indians are my brothers and sisters.\n","i


love my country and i am proud to be an indian.\n"]
f=open("quotes.txt","w")
f.writelines(s)
f.close()
f=open("quotes.txt","r")
t=f.readlines()
ct=0
for c in t:
for i in c:
if(i==" " or i=="." or i=="," or i=="?" or i=="!" or i==";"):
ct+=1
f.close()
print("totalnumber of words in a file is:",ct)

OUTPUT:

Total number of words in a file is: 23


PROGRAM 19

'''Program that reads a text file and then creates a new file where each
character's case is inverted'''
s="India Is My Country"
f=open("abc.txt","w")
f.write(s)
f.close()
f=open("abc.txt","r")
t=f.read()
print("original contents are:",t)
g=open("data.txt","w")
for i in range(len(t)):
if(t[i].isupper()==True):
g.write(t[i].lower())
else:
g.write(t[i].upper())
f.close()
g.close()
g=open("data.txt","r")
print("new contents are:",g.read())

OUTPUT:

original contents are: India Is My Country


new contents are: iNDIA iS mY Country
PROGRAM20

'''Program that receives two lists and creates a third list that contains all
elements of the first followed by all elements of the second'''

l1=eval(input("enter first list elements:"))


l2=eval(input("enter second list elements:"))
l1.extend(l2)
print("third list is",l1)

OUTPUT:

enter first list elements:[1,3,4,5]

enter second list elements:[2,5,8,9]


third list is [1, 3, 4, 5, 2, 5, 8, 9]
PROGRAM 21
WRITE A PROGRAM TO WRITE A DICTIONARY DATA ON TO A CSV FILE

import csv

d = {'name' : 'krunal','age' : 26,'education' : 'Engineering'}

with open('data.csv','w') as f:

for key in d.keys():

f.write("%s,%s\n" %(key,d[key]))

for key in d.keys():

print(key,d[key])

OUTPUT:
PROGRAM 22
GIVEN THE FOLLOWING TABLE

COACH-ID COACH NAME AGE SPORTS D.O.B PAY SEX


1 KUKREJA 35 KARATE 27/03/1996 1000 M
2 RAVINA 34 KARATE 20/01/1998 1200 F
3 KIRAN 34 SQUASH 19/02/1998 2000 M
4 TARUN 33 BASKETBALL 01/01/1998 1500 M
5 ZUBIN 36 SWIMMING 12/02/1998 750 M
6 KETAKI 36 SWIMMING 24/02/1998 800 F
7 ANKITA 39 SQUASH 20/02/1998 2200 F
8 ZAREEN 37 KARATE 22/01/1998 1100 F
9 KHUSH 41 SWIMMING 13/01/1998 900 M

GIVE THE OUTPUT OF THE FOLLOWING SQL STATEMENT

(i) SELECT COUNT (DISTINCT SPORTS) FROM CLUB;

(ii) SELECT MIN (AGE) FROM THE CLUB WHERE SEX=’F’;

(iii) SELECT SUM (PAY) FROM CLUB WHERE Data of Birth>’31/01/1998’;

(iv) SELECT Avg. (PAY) FROM CLUB WHERE Sports=’KARATE’;

OUTPUT:

(i) COUNT(DISTINCT SPORTS)


4

(ii) MIN(AGE)
34

(iii) SUM(PAY)
5750

(iv) AVG(PAY)
1100
PROGRAM 23
GIVEN THE FOLLOWING TABLE

AVG.
NO. NAME STIPEND STREAM MARKS GRADE CLASS
1 KARAN 400 MEDICAL 78.5 B 12A
2 DIVAKAR 450 COMMERCE 89.2 A 11B
3 DIVYA 300 COMMERCE 68.6 C 12C
4 ARUN 650 HUMANITIES 73.1 B 12C
5 SABINA 500 NON-MEDICAL 90.6 A 11A
6 JOHN 400 MEDICAL 75.4 B 12B
7 ROBERT 250 HUMANITIES 64.4 C 11A
8 RUBINA 450 NON-MEDICAL 88.5 A 12A
9 VIKAS 500 NON-MEDICAL 92 A 12A
10 MOHAN 300 COMMERCE 67.5 C 12C

GIVE THE OUTPUT OF THE FOLLOWING SQL STATEMENT

(i) SELECT MIN (AVG. MARKS) FROM STUDENT WHERE AVG. MARKS<75;

(ii) SELECT SUM (STIPEND) FROM STUDENT WHERE GRADE = ‘B’;

(iii) SELECT AVG (STIPEND) FROM STUDENT WHERE CLASS = ‘12A’;

(iv) SELECT COUNT (DISTINCT STREAM) FROM STUDENT;

OUTPUT:

(i) MIN(AVG.MARKS)
64.4

(ii) SUM(STIPEND)
1450

(iii) AVG(STIPEND)
450

(iv) COUNT(DISTINCT STREAM)


4
PROGRAM 24
CONSIDER THE FOLLOWING TABLES SCHOOL & ADMIN & ANSWER THE
FOLLOWING

TABLE:SCHOOL

CODECCCODE TEACHER SUBJECT D.O.B PERIODS EXPERIENCE


1001 RAVISHANKAR ENGLISH 12/03/2000 24 10
1009 PRIYARAI PHYSICS 03/09/1998 26 12
1203 LISANAND ENGLISH 09/04/2000 27 5
1045 YASH RAJ MATHS 24/08/2000 24 15
1123 GAGAN PHYSICS 16/07/1999 28 3
1167 HARISH CHEMISTRY 19/10/1999 27 5
1215 UMESH PHYSICS 11/05/1998 22 16

TABLE:ADMIN

CODECCCODE GENDER DESIGNATION


1001 MALE VICE PRINCIPAL
1009 FEMALE COORDINATOR
1203 FEMALE COORDINATOR
1045 MALE H.O.D.
1123 MALE SENIOR TEACHER
1167 MALE SENIOR TEACHER
1215 MALE H.O.D.

1. SELECT DESIGNATION COUNT(*) FROM ADMIN GROUP BY


DESIGNATION HAVING COUNT (*) <2;
2. SELECT MAX (EXPERIENCE) FROM SCHOOL;
3. SELECT TEACHER FROM SCHOOL WHERE EXPERIENCE > 12 ORDER BY
TEACHER;
4. SELECT COUNT (*) FROM ADMIN GROUP BY GENDER;
OUTPUT:

1. DESIGNATION COUNT(*)
VICE PRINCIPAL 1
2. MAX(EXPERIENCE)
16

3. TEACHER

YASH RAJ
UMESH
4. GENDER COUNT(*)
FEMALE 2
MALE 5
PROGRAM 25
CONSIDER THE FOLLOWING TABLES CUSTOMER & TRANSACTION &
ANSWER THE FOLLOWING

TABLE:CUSTOMER

CNO NAME ADDRESS


101 RICAH JAIN DELHI
102 SURBHISINHA CHENNAI
103 LISATHOMAS BANGALURU
104 IMRAN ALI DELHI
105 ROSHANSINGH CHENNAI

TABLE:TRANSACTION

TRANS. NO. CNO AMOUNT TYPE D.O. TRANS.


T001 101 1500 CREDIT 23/11/2017
T002 102 2000 DEBIT 12/05/2017
T003 103 3000 CREDIT 10/06/2017
T004 104 12000 CREDIT 12/09/2017
T005 105 1000 DEBIT 05/09/2017

1. SELECTCOUNT (*), AVG (AMOUNT) FROM TRANSACTION WHERE


D.O.TRANS. >=’01/06/2017’;
2. SELECT CNO, COUNT(*), MAX(AMOUNT) FROM TRANSACTION
GROUP BY CNO HAVING COUNT(*)>1;
3. SELECT CNO, CNAME FROM CUSTOMER, WHERE ADDRESS NOT IN
(‘DELHI’,’BENGALURU’);
4. SELECT DISTINCT CNO FROM TRANSACTION;
OUTPUT:
1. COUNT(*) AVG(AMOUNT)

4 4375

2. NO OUTPUT
3. CNO CNAME

102 SURBHI SINHA

105 ROSHAN SINGH

4. DISTINCT(CNO)

101
102
103
104
105
PROGRAM 26
WRITE SQL COMMANDS FOR THE FOLLOWING ON THE BASIS OF GIVEN
TABLE

 TO SHOW ALL INFORMATION ABOUT THE TEACHER OF ‘HISTORY’


DEPARTMENT

 TO LIST NAME OF FEMALE TEACHER WHO ARE IN ‘COMPUTER’


DEPARTMENT

 TO LIST NAME OF ALL TEACHER WITH THEIR DATE OF JOINING IN


ASCENDING ORDER

 INSERT A NEW ROW IN A TABLE HAVE FOLLOWING VALUES

9,’ANU’,35,’HISTORY’,’02/01/1999’,3500,’F’

DATE OF
NO. NAME AGE DEPARTMENT JOINING SALARY SEX
1 JUGAL 34 COMPUTER 10/01/1997 12000 M
2 SHARMILA 31 HISTORY 24/03/1998 20000 F
3 SANDEEP 32 MATH 12/12/1996 30000 M
4 SANGETA 35 HISTORY 01/07/1999 40000 F
5 RAKESH 42 MATH 05/09/1997 25000 M
6 SHYAM 50 HISTORY 27/06/1997 30000 M
7 SHIV OM 44 COMPUTER 25/02/1997 21000 M
8 SHALAKHA 33 MATH 31/07/1997 20000 F

OUTPUT:

 SELECT * FROM teacher WHERE Department = ‘History’;

 SELECT NAME FROM teacher WHERE Sex = ‘F’ AND


Department = ‘Computer’;

 SELECT NAME FROM teacher ORDER BY Date of joining;

 INSERT INTO teacher

VALUES (9 , ’ANU’ , 35 , ’HISTORY’ , ’02/01/1999’ , 3500 , ’F’);


PROGRAM 27

'''Write a python program that displays first three rows fetched from student
table of mysql database'''

import mysql.connector as s
mycon=s.connect(host="localhost",user="jbs",passwd="jbs",database="test
")
if(mycon.is_connected()):
print("connection established successfully")
cursor=mycon.cursor()
cursor.execute("select * from student")
data=cursor.fetchmany(3)
for i in data:
print(i)
mycon.close()

OUTPUT:
connection established successfully
(1,’amit’,’A’,’Good’)
(2,’ajay’,’B’,’Average’)
(3,’jatin’,’A’,’Good’)
PROGRAM 28

'''Write a python program to insert a new record in student table'''

import mysql.connector as s
mycon=s.connect(host="localhost",user="jbs",passwd="jbs",database="test
")
if(mycon.is_connected()):
print("connection established successfully")
cursor=mycon.cursor()
d="insert into
student(rno,name,grade,remarks)values({},'{}','{}','{}')".format(4,'amita','B',
'average')
cursor.execute(d)
mycon.commit()
data=cursor.fetchall()
for i in data:
print(i)
mycon.close()

output:

connection established successfully


(1,’amit’,’A’,’Good’)
(2,’ajay’,’B’,’Average’)
(3,’jatin’,’A’,’Good’)
(4,’amita’,’B’,’average’)
PROGRAM 29

'''Write a python program to delete the records of the student having grade
'B''''

import mysql.connector as s
mycon=s.connect(host="localhost",user="jbs",passwd="jbs",database="test
")
if(mycon.is_connected()):
print("connection established successfully")
cursor=mycon.cursor()
d="delete from student where grade='{}'".format('B')
cursor.execute(d)
mycon.commit()
data=cursor.fetchall()
for i in data:
print(i)
mycon.close()

output:

connection established successfully


(1,’amit’,’A’,’Good’)
(3,’jatin’,’A’,’Good’)
PROGRAM 30

'''Write a python program to update the grade from A to A+ in student table


of mysql'''

import mysql.connector as s
mycon=s.connect(host="localhost",user="jbs",passwd="jbs",database="test
")
if(mycon.is_connected()):
print("connection established successfully")
cursor=mycon.cursor()
d="update student set grade='{}'".format('A','A+')
cursor.execute(d)
mycon.commit()
data=cursor.fetchall()
for i in data:
print(i)
mycon.close()

output:

connection established successfully


(1,’amit’,’A+’,’Good’)
(3,’jatin’,’A+’,’Good’)

You might also like