Python Programs
Python Programs
'''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" '''
OUTPUT:
All indians are my brothers and sisters
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
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
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
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
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:
'''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:
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)
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:
OUTPUT:
total number of rows:3
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
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):
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
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
OUTPUT:
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
OUTPUT:
PROGRAM 18
OUTPUT:
'''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:
'''Program that receives two lists and creates a third list that contains all
elements of the first followed by all elements of the second'''
OUTPUT:
import csv
with open('data.csv','w') as f:
f.write("%s,%s\n" %(key,d[key]))
print(key,d[key])
OUTPUT:
PROGRAM 22
GIVEN THE FOLLOWING TABLE
OUTPUT:
(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
(i) SELECT MIN (AVG. MARKS) FROM STUDENT WHERE AVG. MARKS<75;
OUTPUT:
(i) MIN(AVG.MARKS)
64.4
(ii) SUM(STIPEND)
1450
(iii) AVG(STIPEND)
450
TABLE:SCHOOL
TABLE:ADMIN
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
TABLE:TRANSACTION
4 4375
2. NO OUTPUT
3. CNO CNAME
4. DISTINCT(CNO)
101
102
103
104
105
PROGRAM 26
WRITE SQL COMMANDS FOR THE FOLLOWING ON THE BASIS OF GIVEN
TABLE
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:
'''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
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:
'''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:
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: