0% found this document useful (0 votes)
18 views58 pages

Harshit CS FILE

computer science practical lists

Uploaded by

harshit01422
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views58 pages

Harshit CS FILE

computer science practical lists

Uploaded by

harshit01422
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 58

L5 XII

"""
Program List : L7
Program No : 2
Developed By : Harshit (XII-H)
Date : 27-11-2024
"""

def pushbook(stack, code, title):


stack.append((code, title))
print("Pushed book:", title)
def popbook(stack):
if not stack:
print("Stack is EMPTY")
else:
print("Popped book:", stack.pop())
def menu():
stack = []
while True:
print("1. PUSH BOOK")
print("2. POP BOOK")
print("3. Exit")
choice = int(input("Enter choice: "))
if choice == 1:
c = int(input("Enter book code: "))
t = input("Enter book title: ")
pushbook(stack, c, t)
elif choice == 2:
popbook(stack)
elif choice == 3:
break
else:
print("Invalid choice")

menu()

"""OUTPUT
1. PUSH BOOK
2. POP BOOK
3. Exit
Enter choice: 1
Enter book code: 043
Enter book title: maths
Pushed book: maths
1. PUSH BOOK
2. POP BOOK
3. Exit
Enter choice: 1
Enter book code: 401
Enter book title: eng
Pushed book: eng
1. PUSH BOOK
2. POP BOOK
3. Exit
Enter choice: 2
Popped book: (401, 'eng')
1. PUSH BOOK
2. POP BOOK
3. Exit
Enter choice: 3
"""

OUTPUT:
1. PUSH BOOK
2. POP BOOK
3. Exit
Enter choice: 1
Enter book code: 043
Enter book title: maths
Pushed book: maths
1. PUSH BOOK
2. POP BOOK
3. Exit
Enter choice: 1
Enter book code: 401
Enter book title: eng
Pushed book: eng
1. PUSH BOOK
2. POP BOOK
3. Exit
Enter choice: 2
Popped book: (401, 'eng')
1. PUSH BOOK
2. POP BOOK
3. Exit
Enter choice: 3

"""
Program List : L7
Program No : 1
Developed By : Harshit (XII-H)
Date : 26-11-2024
"""
def push(stack, value):
stack.append(value)
print("Pushed:", value)
def pop(stack):
if not stack:
print("Stack is EMPTY")
else:
print("Popped:", stack.pop())
def menu():
stack = []
while True:
print("1. PUSH")
print("2. POP")
print("3. Exit")
choice = int(input("Enter choice: "))
if choice == 1:
value = int(input("Enter value: "))
push(stack, value)
elif choice == 2:
pop(stack)
elif choice == 3:
break
else:
print("Invalid choice")
menu()

"""OUTPUT
1. PUSH
2. POP
3. Exit
Enter choice: 1
Enter value: 12
Pushed: 12
1. PUSH
2. POP
3. Exit
Enter choice: 13
Invalid choice
1. PUSH
2. POP
3. Exit
Enter choice: 2
Popped: 12
1. PUSH
2. POP
3. Exit
Enter choice: 3
"""

OUTPUT:
OUTPUT
1. PUSH
2. POP
3. Exit
Enter choice: 1
Enter value: 12
Pushed: 12
1. PUSH
2. POP
3. Exit
Enter choice: 13
Invalid choice
1. PUSH
2. POP
3. Exit
Enter choice: 2
Popped: 12
1. PUSH
2. POP
3. Exit
Enter choice: 3

"""
Program List : L7
Program No : 3
Developed By : Harshit (XII-H)
Date : 27-11-2024
"""

def pushitems(itemlist, stack):


for item in itemlist:
if item[2] < 10:
stack.append(item)
print("Pushed:", item)
def popitem(stack):
if not stack:
return "No reorder ITEM"
else:
return stack.pop()
def displaystack(stack):
if not stack:
print("No reorder ITEM")
else:
print("Stack:", stack)
def menu():
itemlist = [[101, "Notebook", 5],[102, "Pen", 15],[103, "Eraser",
3],[104, "Pencil", 8],[105, "Marker", 12]]
stack = []
pushitems(itemlist, stack)
while True:
print("1. POP")
print("2. DISPLAY")
print("3. Exit")
choice = int(input("Enter choice: "))
if choice == 1:
result = popitem(stack)
if result == "No reorder ITEM":
print(result)
break
else:
print("Popped:", result)
elif choice == 2:
displaystack(stack)
elif choice == 3:
break
else:
print("Invalid choice")
menu()

"""OUTPUT
Pushed: [101, 'Notebook', 5]
Pushed: [103, 'Eraser', 3]
Pushed: [104, 'Pencil', 8]
1. POP
2. DISPLAY
3. Exit
Enter choice: 1
Popped: [104, 'Pencil', 8]
1. POP
2. DISPLAY
3. Exit
Enter choice: 2
Stack: [[101, 'Notebook', 5], [103, 'Eraser', 3]]
1. POP
2. DISPLAY
3. Exit
Enter choice: 3
"""

OUTPUT
Pushed: [101, 'Notebook', 5]
Pushed: [103, 'Eraser', 3]
Pushed: [104, 'Pencil', 8]
1. POP
2. DISPLAY
3. Exit
Enter choice: 1
Popped: [104, 'Pencil', 8]
1. POP
2. DISPLAY
3. Exit
Enter choice: 2
Stack: [[101, 'Notebook', 5], [103, 'Eraser', 3]]
1. POP
2. DISPLAY
3. Exit
Enter choice: 3

"""
Program List : L7
Program No : 4
Developed By : Harshit (XII-H)
Date : 27-11-2024
"""
def pushname(stack, name):
stack.append(name)
print("Pushed:", name)
def popname(stack):
if not stack:
print("Stack is EMPTY")
else:
print("Popped:", stack.pop())
def snames(stack):
if not stack:
print("Stack is EMPTY")
else:
print("Stack:", stack)
def menu():
stack = []
while True:
print("1. PUSH NAME")
print("2. POP NAME")
print("3. SHOW STACK")
print("4. Exit")
choice = int(input("Enter choice: "))
if choice == 1:
name = input("Enter name: ")
pushname(stack, name)
elif choice == 2:
popname(stack)
elif choice == 3:
snames(stack)
elif choice == 4:
break
else:
print("Invalid choice")
menu()

"""OUTPUT
1. PUSH NAME
2. POP NAME
3. SHOW STACK
4. Exit
Enter choice: 1
Enter name: naina
Pushed: naina
1. PUSH NAME
2. POP NAME
3. SHOW STACK
4. Exit
Enter choice: 1
Enter name: kartik
Pushed: kartik
1. PUSH NAME
2. POP NAME
3. SHOW STACK
4. Exit
Enter choice: 1
Enter name: neha
Pushed: neha
1. PUSH NAME
2. POP NAME
3. SHOW STACK
4. Exit
Enter choice: 2
Popped: neha
1. PUSH NAME
2. POP NAME
3. SHOW STACK
4. Exit
Enter choice: 3
Stack: ['naina', 'kartik']
1. PUSH NAME
2. POP NAME
3. SHOW STACK
4. Exit
Enter choice: 4
"""

OUTPUT:
1. PUSH NAME
2. POP NAME
3. SHOW STACK
4. Exit
Enter choice: 1
Enter name: naina
Pushed: naina
1. PUSH NAME
2. POP NAME
3. SHOW STACK
4. Exit
Enter choice: 1
Enter name: kartik
Pushed: kartik
1. PUSH NAME
2. POP NAME
3. SHOW STACK
4. Exit
Enter choice: 1
Enter name: neha
Pushed: neha
1. PUSH NAME
2. POP NAME
3. SHOW STACK
4. Exit
Enter choice: 2
Popped: neha
1. PUSH NAME
2. POP NAME
3. SHOW STACK
4. Exit
Enter choice: 3
Stack: ['naina', 'kartik']
1. PUSH NAME
2. POP NAME
3. SHOW STACK
4. Exit
Enter choice: 4
L2 XII
"""
Program List : List -02
Program No : 01
Developed By : Harshit
Date : 13 June 2024
"""

Eng=[]
Maths=[]
Total=[]
for i in range(5):
n=int(input("Marks in English: "))
k=int(input("Marks in Maths: "))
Eng.append(n)
Maths.append(k)
Total.append(n+k)
print()
print("English Marks: ",Eng)
print("Maths Marks: ",Maths)
print("Total Marks: ",Total)
print()
def cal(L):
mn=L[0];
mx=L[0]
for i in range (len(L)):
if L[i]<=mn:
mn=L[i]
if L[i]>=mx:
mx=L[i]
print("Minimum marks in ",L,":",mn)
print("Maximum marks in ",L,":",mx)
print()
cal(Eng);cal(Maths);cal(Total)
def calavg(L):
Avg=0
for i in range(len(L)):
Avg+=L[i]
Avg=(Avg/len(L))
print("Average marks in",L,":",Avg)
print()
calavg(Eng);calavg(Maths);calavg(Total)

OUTPUT:
Marks in English: 78
Marks in Maths: 89

Marks in English: 90
Marks in Maths: 100

Marks in English: 88
Marks in Maths: 94
Marks in English: 95
Marks in Maths: 97

Marks in English: 34
Marks in Maths: 33

English Marks: [78, 90, 88, 95, 34]


Maths Marks: [89, 100, 94, 97, 33]
Total Marks: [167, 190, 182, 192, 67]

Minimum marks in [78, 90, 88, 95, 34] : 34


Maximum marks in [78, 90, 88, 95, 34] : 95

Minimum marks in [89, 100, 94, 97, 33] : 33


Maximum marks in [89, 100, 94, 97, 33] : 100

Minimum marks in [167, 190, 182, 192, 67] : 67


Maximum marks in [167, 190, 182, 192, 67] : 192

Average marks in [78, 90, 88, 95, 34] : 77.0

Average marks in [89, 100, 94, 97, 33] : 82.6

Average marks in [167, 190, 182, 192, 67] : 159.6

"""
Program List : List -02
Program No : 02
Developed By : Harshit
Date : 13 June 2024
"""
A=[10,20,30,40]
B=[35,25,15,45]
C=[]
for i in range(len(A)):
C.append(A[i]);C.append(B[i])
print(C)
OUTPUT:
[10, 35, 20, 25, 30, 15, 40, 45]
"""
Program List : List -02
Program No : 03
Developed By : Harshit
Date : 13 June 2024
"""

K=[]
def Addvalues(L):
n=int(input("No. of terms : "))
for i in range (n):
k=int(input("Enter an Integer: "))
L.append(k)
def Dispvalues(L):
print("Elements of the list :",end="")
for i in range(len(L)):
print(L[i],end=" ")
print()
def Revcontent(L):
L.reverse()
print("Reversed content: ",L)
def AddEven(L):
Sum=0
for i in L:
if i%2==0:
Sum+=i
print("Sum of Even Elements:",Sum)
def AddOdd(L):
Sum=0
for i in L:
if i%2!=0:
Sum+=i
print("Sum of Odd Elements:,",Sum)
def AddZeroEnd(L):
Sum=0
for i in L:
if i%10==0:
Sum+=i
print("Sum of Multiples of 10:",Sum)
def Show7Ten(L):
print("Elements with 7 at it's tenth place : ",end="")
for i in L:
if (i//10)%10==7:
print(i, end=" ")
print()
def Show20_50(L):
print("Elements between 20 and 50:",end="" )
for i in L:
if i>20 and i<50:
print(i,end=" ")

Addvalues(K)
Dispvalues(K)
Revcontent(K)
AddEven(K)
AddOdd(K)
AddZ
OUTPUT:
Enter an Integer: 78
Enter an Integer: 67
Enter an Integer: 87
Enter an Integer: 12
Enter an Integer: 25
Enter an Integer: 70
Enter an Integer: 50
Elements of the list :78 67 87 12 25 70 50
Reversed content: [50, 70, 25, 12, 87, 67, 78]
Sum of Even Elements: 210
Sum of Odd Elements:, 179
Sum of Multiples of 10: 120
Elements with 7 at it's tenth place : 70 78
Elements between 20 and 50:25

"""
Program List : List -02
Program No : 04
Developed By : Harshit
Date : 13 June 2024
"""
K=[]
def Addvalues(L):
n=int(input("No. of terms : "))
for i in range (n):
k=int(input("Enter an Integer: "))
L.append(k)
def Dispvalues(L):
print("Elements of the list :",end="")
for i in range(len(L)):
print(L[i],end=" ")
print()
def SwapPair(L):
for i in range (0,len(L),2):
L[i],L[i+1]=L[i+1],L[i]
def SwapHalf(L):
for i in range(len(L)//2):
L[i],L[len(L)//2+i]=L[len(L)//2+i],L[i]
Addvalues(K)
Dispvalues(K)
SwapPair(K)
Dispvalues(K)
SwapHalf(K)
Dispvalues(K)
OUTPUT:
No. of terms : 6
Enter an Integer: 10
Enter an Integer: 20
Enter an Integer: 30
Enter an Integer: 40
Enter an Integer: 50
Enter an Integer: 60
Elements of the list :10 20 30 40 50 60
Elements of the list :20 10 40 30 60 50
Elements of the list :30 60 50 20 10 40

"""
Program List : List -02
Program No : 05
Developed By : Harshit
Date : 13 June 2024
"""
K=[]
def AddCity(C):
n=int(input("No. of cities : "))
for i in range (n):
k=input("Name of the city : ")
C.append(k)
def AllUcase(C):
for i in range (len(C)):
C[i]=(C[i]).upper()
def ShowDisp(C):
print("The cities are : ",end="")
for i in C:
print(i,end=" ")
print()
def Arrange(C):
for i in C:
i=i.title()
C.sort(reverse=False)
def ShortNameCities(C):
print("cities with less than or equal to 4 characters: ",end="")
for i in C:
if len(i)<4 or len(i)==4:
print(i,end=" ")
print()
def BigNameCities(C):
print("cities with more than 4 characters: ",end="")
for i in C:
if len(i)>4:
print(i,end=" ")
print()
def CityNameLength(C):
print("No. of alphabets in each city: ",end='')
for i in C:
print(len(i),end=" ")
AddCity(K)
ShowDisp(K)
AllUcase(K)
ShowDisp(K)
Arrange(K)
ShowDisp(K)
ShortNameCities(K)
BigNameCities(K)
CityNameLength(K)
'''
OUTPUT:
No. of cities : 7
Name of the city : Ajmer
Name of the city : Pune
Name of the city : Ahemdabad
Name of the city : gWalior
Name of the city : Indore
Name of the city : bAnglore
Name of the city : MUMBAI
The cities are : Ajmer Pune Ahemdabad gWalior Indore bAnglore MUMBAI
The cities are : AJMER PUNE AHEMDABAD GWALIOR INDORE BANGLORE MUMBAI
The cities are : AHEMDABAD AJMER BANGLORE GWALIOR INDORE MUMBAI PUNE
cities with less than or equal to 4 characters: PUNE
cities with more than 4 characters: AHEMDABAD AJMER BANGLORE GWALIOR
INDORE MUMBAI
No. of alphabets in each city: 9 5 8 7 6 6 4 '''

"""
Program List : List -02
Program No : 06
Developed By : Harshit
Date : 13 June 2024
"""
B=[]
def AddBooks(B):
n=int(input("No. of books : "))
for i in range (n):
k=input("Name of the book: ")
B.append(k)
def AllIndia(B):
print("Titles of all the books, which contain India:",end="")
for k in B:
k.title()
if "India" in (k.split()):
print(k, end=" ")
print()

def ShowBooks(B):
print("Books:" ,end="")
for i in B:
print(i,end=" ")
print()
def SingleWords(B):
print("single word titles books: ",end="")
for i in B:
if len(i.split())==1:
print(i.upper(),end=" ")
print()
def CountSingle(B):
print(" No.of single word titles books: ",end="")
c=0
for i in B:
if len(i.split())==1:
c+=1
print(c)
def ThetoA(B):
for i in range (len(B)):
if "The" in ((B[i]).title()):
B[i]=B[i].replace("The","A")
AddBooks(B)
ShowBooks(B)
AllIndia(B)
SingleWords(B)
CountSingle(B)
ThetoA(B)
'''
OUTPUT:
No. of books : 7
Name of the book: Discovery of India
Name of the book: Dune
Name of the book: India after gandhi
Name of the book: The White Tiger
Name of the book: Atomic Habits
Name of the book: Rebecca
Name of the book: Why I am a Hindu?
Books:Discovery of India Dune India after gandhi The White Tiger Atomic
Habits Rebecca Why I am a Hindu?
Titles of all the books, which contain India:Discovery of India India
after gandhi
single word titles books: DUNE REBECCA
No.of single word titles books: 2
'''

"""
Program List : List -02
Program No : 07
Developed By : Harshit
Date : 13 June 2024
"""
T=(10,40,20,30,50,70)
L=list(T)
L.sort(reverse=True)
print("Sorted content: ",tuple(L))
print("Sum: ",sum(T))
print("Maximum: ", max(T))
print("Minimum: ", min(T))
J=[]
for i in range(0,len(T),2):
m=T[i]+T[i+1]
J.append(m)
print("Sum of Adjacent pairs: ",J)
for i in range (len(T)):
for j in range(len(T)):
if T[i]+T[j] in T:
print("Pairs are ",i+1 ,"and",j+1 ,"i.e,",T[i],T[j],"=",T[i]+T[j])
'''Sorted content: (70, 50, 40, 30, 20, 10)
OUTPUT:
Sum: 220
Maximum: 70
Minimum: 10
Sum of Adjacent pairs: [50, 50, 120]
Pairs are 1 and 1 i.e, 10 10 = 20
Pairs are 1 and 2 i.e, 10 40 = 50
Pairs are 1 and 3 i.e, 10 20 = 30
Pairs are 1 and 4 i.e, 10 30 = 40
Pairs are 2 and 1 i.e, 40 10 = 50
Pairs are 2 and 4 i.e, 40 30 = 70
Pairs are 3 and 1 i.e, 20 10 = 30
Pairs are 3 and 3 i.e, 20 20 = 40
Pairs are 3 and 4 i.e, 20 30 = 50
Pairs are 3 and 5 i.e, 20 50 = 70
Pairs are 4 and 1 i.e, 30 10 = 40
Pairs are 4 and 2 i.e, 30 40 = 70
Pairs are 4 and 3 i.e, 30 20 = 50
Pairs are 5 and 3 i.e, 50 20 = 70
'''

"""
Program List : List -02
Program No : 08
Developed By : Harshit
Date : 13 June 2024
"""
WD=(1,2,3,4,5,6,7)
WDN=['SUN','MON','TUE','WED','THU','FRI','SAT']
W={}
for i in range(len(WD)):
W[WD[i]]=WDN[i]
print("INITIAL: ",W)
WDN=WDN[1:]+WDN[:1]
for i in range(len(WD)):
W[WD[i]]=WDN[i]
print("MODIFIED :",W)
MyDays={}
OfficeDays={}
for i in W.keys():
if i==2 or i==4 or i==7:
MyDays[i]=W[i]
else:
OfficeDays[i]=W[i]
print("My Days: ",MyDays)
print("Office Days: ",OfficeDays)
OUTPUT:
'''INITIAL: {1: 'SUN', 2: 'MON', 3: 'TUE', 4: 'WED', 5: 'THU', 6: 'FRI',
7: 'SAT'}
MODIFIED : {1: 'MON', 2: 'TUE', 3: 'WED', 4: 'THU', 5: 'FRI', 6: 'SAT', 7:
'SUN'}
My Days: {2: 'TUE', 4: 'THU', 7: 'SUN'}
Office Days: {1: 'MON', 3: 'WED', 5: 'FRI', 6: 'SAT'}'''

"""
Program List : List -02
Program No : 09
Developed By : Harshit
Date : 13 June 2024
"""

TL=('RED','YELLOW','GREEN')
TM=('STOP','BE READY TO START/STOP','GO')
CL=[]
for i in range (10):
n=str(input("Enter a color: "))
CL.append(n)
for k in range(10):
if (CL[k]).upper() in TL:
print(CL[k]," :TRAFFIC LIGHT")
else:
print(CL[k]," :NOT TRAFFIC LIGHT")
TLM={}
for k in range(3):
TLM[TL[k]]=TM[k]
print("Required output:",TLM)
'''
OUTPUT:
Enter a color: Grey
Enter a color: Indigo
Enter a color: Red
Enter a color: Blue
Enter a color: Orange
Enter a color: Yellow
Enter a color: Black
Enter a color: Green
Enter a color: Purple
Enter a color: Pink
Grey :NOT TRAFFIC LIGHT
Indigo :NOT TRAFFIC LIGHT
Red :TRAFFIC LIGHT
Blue :NOT TRAFFIC LIGHT
Orange :NOT TRAFFIC LIGHT
Yellow :TRAFFIC LIGHT
Black :NOT TRAFFIC LIGHT
Green :TRAFFIC LIGHT
Purple :NOT TRAFFIC LIGHT
Pink :NOT TRAFFIC LIGHT
Required output: {'RED': 'STOP', 'YELLOW': 'BE READY TO START/STOP',
'GREEN': 'GO'}
'''

L3 XII
"""
Program List : L3
Program No : 1
Developed By : Harshit (XII-H)
Date : 3-07-2024
"""
def Get_Story():
F=open('NOTES.TXT','w')
while True:
L=input("Line:")
F.write(L+"\n")
M=input("More(Y/N)")
if M in ['N','n']:
break
Get_Story()

def Words():
F=open('NOTES.TXT')
for eachline in F:
s=F.readlines()
for i in s:
print(i,end="")

Words()

def AllWords():
F=open('NOTES.TXT')
s=F.read()
c=0
for i in s.split():
print("words",i)
c+=1
print("number of words",c)

AllWords()

OUTPUT:
Line:hello
More(Y/N)Y
Line:no
More(Y/N)N
no
words hello
words no
number of words 2

"""
Program List : L3
Program No : 2
Developed By : Harshit (XII-H)
Date : 3-07-2024
"""
def CreateNotes():
F=open('NOTES.TXT','w')
while True:
ch=input('Enter text: ')
F.write(ch+'\n')
T=input('More? ')
if T in 'Nn':
break
F.close()

def CountAVD():
F=open('NOTES.TXT')
R=F.read()
S=R.split()
a,v,d=0,0,0
for i in S:
for j in i:
if j.isalpha()==True:
a+=1
if j in 'AEIOUaeiou':
v+=1
if j.isdigit()==True:
d+=1
print('No. of alphabets:',a)
print('No. of vowels:',v)
print('No. of digits:',d)
F.close()

def ShowNotes():
F=open('NOTES.TXT')
R=F.read()
print(R)
F.close()

def RevText():
F=open('NOTES.TXT')
R=F.read()
S=R.split('\n')
for i in S:
if i.startswith('T')==True:
print(i[::-1])
F.close()
def CountLines():
F=open('NOTES.TXT')
R=F.read()
S=R.split('\n')
print('The no. of lines are', len(S)-1)
F.close()

count=0
while True:
a=input('Create?-(a) Count?-(b) Show?-(c) Reverse Lines Starting with
T-(d) Count Lines?-(e): ')
if count==0 and a in 'BbCcDdEe':
print('Invalid input')
elif a in 'aA':
CreateNotes()
elif a in 'bB':
CountAVD()
elif a in 'cC':
ShowNotes()
elif a in 'dD':
RevText()
elif a in 'eE':
CountLines()
count+=1
T=input('Continue?(Y/N): ')
if T in 'Nn':
break
OUTPUT:
Create?-(a) Count?-(b) Show?-(c) Reverse Lines Starting with T-(d) Count
Lines?-(e): d
Invalid input
Continue?(Y/N): Y
Create?-(a) Count?-(b) Show?-(c) Reverse Lines Starting with T-(d) Count
Lines?-(e): c
naina

Continue?(Y/N): Y
Create?-(a) Count?-(b) Show?-(c) Reverse Lines Starting with T-(d) Count
Lines?-(e): a
Enter text: hii
More? Nn
Continue?(Y/N): N

"""
Program List : L3
Program No : 3
Developed By : Harshit (XII-H)
Date : 3-07-2024
"""
def Add2Diary():
F=open('DIARY.TXT','w')
while True:
d=input('Enter date as DD-Mon-YYYY: ')
c=input('Enter: ')
F.write(d+''+c+'\n')
T=input('More? ')
if T in 'Nn':
break
F.close()

def MonthlyActs(Mon):
m=Mon
F=open('DIARY.TXT')
R=F.readlines()
for i in R:
if i[3:6]==m:
print(i)
F.close()

def ShowRevision(Topic):
t=Topic
F=open('DIARY.TXT')
R=F.read()
c=0
for i in R.split():
if t in i :
c+=1
print(t,'occurs', c,'times.')
F.close()

def LastAct():
F=open('DIARY.TXT')
R=F.readlines()
for i in R:
print(i.split(',')[-1])

count=0
while True:
a=input('Add?-(a) MonthlyActivities?-(b) ShowRevision?-(c) Last
Activity?-(d): ')
if count==0 and a in 'BbCcDdEe':
print('Invalid input')
elif a in 'aA':
Add2Diary()
elif a in 'bB':
c=input('Enter month: ')
MonthlyActs(c)
elif a in 'cC':
Topic=input('Enter topic: ')
ShowRevision(Topic)
elif a in 'dD':
LastAct()
count+=1
T=input('Continue?(Y/N): ')
if T in 'Nn':
break
OUTPUT:
Add?-(a) MonthlyActivities?-(b) ShowRevision?-(c) Last Activity?-(d): a
Enter date as DD-Mon-YYYY: 27-12-2006
Enter: 4
More? N
Continue?(Y/N): Y
Add?-(a) MonthlyActivities?-(b) ShowRevision?-(c) Last Activity?-(d): b
Enter month: may
Continue?(Y/N): Y
Add?-(a) MonthlyActivities?-(b) ShowRevision?-(c) Last Activity?-(d): c
Enter topic: badminton
badminton occurs 0 times.
Continue?(Y/N): Y
Add?-(a) MonthlyActivities?-(b) ShowRevision?-(c) Last Activity?-(d): d
27-12-20064

Continue?(Y/N): N

"""
Program List : L3
Program No : 4
Developed By : Harshit (XII-H)
Date : 5-07-2024
"""

import random

def Create():
N=int(input("Enter 'N': "))
SandC={}
for i in range(N):
K=input('Indian State: ')
C=input('Capital: ')
SandC.update({K:C})
print(SandC)
c=input('Confirm transfer to text file(Y/N)?: ')
if c in 'Yy':
F=open('CAPITALS.TXT','w')
for i in SandC:
F.write(i+'*'+SandC[i]+'\n')
F.close()

def Check():
s=input('Enter state name: ')
F=open('CAPITALS.TXT','r')
L=F.readlines()
for i in L:
if s in i:
j=i.split('*')
print(j[1])
F.close()

def Quiz():
F=open('CAPITALS.TXT','r')
L=F.readlines()
D=[]
for i in L:
j=i.split('*')
D.append([j[0],j[1]])
s=0
w=0
while True:
if s==5 or w==3:
break
random.shuffle(D)
for i in D:
print(i[0])
ans=input('Capital?: ')
if ans+'\n'==i[1]:
print('Correct!')
s+=1
else:
print('Wrong!')
print('Correct answer:',i[1])
w+=1
if s==5 or w==3:
break
print('Score:',s)
F.close()

while True:
ch=input('Create?-(A) Check?(B) Quiz?(C): ')
if ch in 'Aa':
Create()
elif ch in 'Bb':
Check()
elif ch in 'Cc':
Quiz()
else:
print('Invalid input')
T=input('Continue?(Y/N): ')
if T in 'Nn':
break
OUTPUT:
Create?-(A) Check?(B) Quiz?(C): A
Enter 'N': 2
Indian State: Goa
Capital: panaji
Indian State: rajasthan
Capital: jaipur
{'Goa': 'panaji', 'rajasthan': 'jaipur'}
Confirm transfer to text file(Y/N)?: Y
Continue?(Y/N): Y
Create?-(A) Check?(B) Quiz?(C): B
Enter state name: odisha
Continue?(Y/N): Y
Create?-(A) Check?(B) Quiz?(C): C
rajasthan
Capital?: jaipur
Correct!
Goa
Capital?: mumbai
Wrong!
Correct answer: panaji

rajasthan
Capital?: goa
Wrong!
Correct answer: jaipur

Goa
Capital?: Panaji
Wrong!
Correct answer: panaji

Score: 1
Continue?(Y/N): N

"""
Program List : L3
Program No : 5
Developed By : Harshit (XII-H)
Date : 5-07-2024
"""
def CreateStory():
F=open('STORY.TXT','w')
while True:
ch=input('Enter text: ')
F.write(ch+'\n')
T=input('More? ')
if T in 'Nn':
break
F.close()

def BigLines():
F=open('STORY.TXT','r')
L=F.readlines()
for i in L:
if len(i)>80:
print(i[0:len(i)-1])
F.close()
def TranDelhi():
F=open('STORY.TXT','r')
L=F.readlines()
D=[]
for i in L:
if 'DELHI' in i.upper():
D+=[i]
F.close()
W=open('DELHI.TXT','w')
for i in D:
W.write(i)
W.close()

def Recreate():
F=open('STORY.TXT','r')
L=F.readlines()
ND=[]
for i in L:
if 'DELHI' not in i.upper():
ND+=[i]
F.close()

W=open('NEWSTORY.TXT','w')
for i in ND:
W.write(i)
W.close()

f1=open('NEWSTORY.TXT','r')
r=f1.read()
f1.close()

f2=open('STORY.TXT','a')
f2.write(r)
f2.close()

while True:
ch=input('Create?-(A) Read Big Lines?(B) Delhi Story?(C) New
Story?(D): ')
if ch in 'Aa':
CreateStory()
elif ch in 'Bb':
BigLines()
elif ch in 'Cc':
TranDelhi()
elif ch in 'Dd':
Recreate()
else:
print('Invalid input')
T=input('Continue?(Y/N): ')
if T in 'Nn':
break
OUTPUT:
Create?-(A) Read Big Lines?(B) Delhi Story?(C) New Story?(D): A
Enter text: Hi
More? Y
Enter text: bye
More? Nn
Continue?(Y/N): Y
Create?-(A) Read Big Lines?(B) Delhi Story?(C) New Story?(D): B
Continue?(Y/N): N

"""
Program List : L3
Program No : 6
Developed By : Harshit (XII-H)
Date : 5-07-2024
"""

def CreateLog():
F=open('LOG.TXT','a')
while True:
ch=input('Enter text: ')
F.write(ch+'\n')
T=input('More? ')
if T in 'Nn':
break
F.close()

def CompletedWork():
F=open('LOG.TXT','r')
L=F.readlines()
for i in L:
if 'COMPLETED' in i.upper():
print(i)
F.close()

def CountPending():
F=open('LOG.TXT','r')
L=F.readlines()
c=0
for i in L:
if 'DOING' in i.upper() or 'PENDING' in i.upper() or 'HALFWAY' in
i.upper():
c+=1
print('No. of lines with pending work:',c)
F.close()

def ShowLog():
F=open('LOG.TXT','r')
print(F.read())
F.close()

while True:
ch=input('Create?-(A) Completed Work?(B) No. of pending work?(C)
Show?(D): ')
if ch in 'Aa':
CreateLog()
elif ch in 'Bb':
CompletedWork()
elif ch in 'Cc':
CountPending()
elif ch in 'Dd':
ShowLog()
else:
print('Invalid input')
T=input('Continue?(Y/N): ')
if T in 'Nn':
break
OUTPUT:
Create?-(A) Completed Work?(B) No. of pending work?(C) Show?(D): A
Enter text: hell
More? Y
Enter text: bell
More? yes
Enter text: BYEBYE
More? No
Enter text: oct
More? Nn
Continue?(Y/N): Y
Create?-(A) Completed Work?(B) No. of pending work?(C) Show?(D): C
No. of lines with pending work: 0
Continue?(Y/N): Y
Create?-(A) Completed Work?(B) No. of pending work?(C) Show?(D): B
Continue?(Y/N): Y
Create?-(A) Completed Work?(B) No. of pending work?(C) Show?(D): D
hell
bell
BYEBYE
oct

Continue?(Y/N): N

L4 XII
"""
Program List : L4
Program No : 1
Developed By : Harshit (XII-H)
Date : 16-08-2024
"""

import pickle

def Enrol():
with open("CANDIDATE.DAT", "ab") as file:
candidate_no = int(input("Enter Candidate No: "))
cname = input("Enter Candidate Name: ")
score = float(input("Enter Score: "))
candidate = [candidate_no, cname, score]
pickle.dump(candidate, file)
print("Candidate added successfully.")

def GetPass():
try:
with open("CANDIDATE.DAT", "rb") as file:
print("Candidates who passed (Score >= 50):")
while True:
try:
candidate = pickle.load(file)
if candidate[2] >= 50:
print(candidate)
except EOFError:
break
except FileNotFoundError:
print("No records found. The file does not exist.")

def ShowAll():
try:
with open("CANDIDATE.DAT", "rb") as file:
print("All Candidates:")
while True:
try:
candidate = pickle.load(file)
print(candidate)
except EOFError:
break
except FileNotFoundError:
print("No records found. The file does not exist.")

def AverageScore():
try:
with open("CANDIDATE.DAT", "rb") as file:
total_score = 0
count = 0
while True:
try:
candidate = pickle.load(file)
total_score += candidate[2]
count += 1
except EOFError:
break
if count > 0:
return total_score / count
else:
return 0
except FileNotFoundError:
print("No records found. The file does not exist.")
return 0
def menu():
while True:
print("\nMenu:")
print("1. Enroll new candidate")
print("2. Display candidates who passed")
print("3. Display all candidates")
print("4. Calculate average score")
print("5. Exit")
choice = int(input("Enter your choice: "))

if choice == 1:
Enrol()
elif choice == 2:
GetPass()
elif choice == 3:
ShowAll()
elif choice == 4:
avg_score = AverageScore()
print(f"Average Score: {avg_score:.2f}")
elif choice == 5:
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")
menu()
OUTPUT:
Menu:
1. Enrol new candidate
2. Display candidates who passed
3. Display all candidates
4. Calculate average score
5. Exit
Enter your choice: 1
Enter Candidate No: 1
Enter Candidate Name: ranjan
Enter Score: 98
Candidate added successfully.

Menu:
1. Enrol new candidate
2. Display candidates who passed
3. Display all candidates
4. Calculate average score
5. Exit
Enter your choice: 1
Enter Candidate No: 2
Enter Candidate Name: kirti
Enter Score: 49
Candidate added successfully.

Menu:
1. Enrol new candidate
2. Display candidates who passed
3. Display all candidates
4. Calculate average score
5. Exit
Enter your choice: 3
All Candidates:
[1, 'ranjan', 98.0]
[2, 'kirti', 49.0]

Menu:
1. Enrol new candidate
2. Display candidates who passed
3. Display all candidates
4. Calculate average score
5. Exit
Enter your choice: 2
Candidates who passed (Score >= 50):
[1, 'ranjan', 98.0]

Menu:
1. Enrol new candidate
2. Display candidates who passed
3. Display all candidates
4. Calculate average score
5. Exit
Enter your choice: 4
Average Score: 73.50

Menu:
1. Enrol new candidate
2. Display candidates who passed
3. Display all candidates
4. Calculate average score
5. Exit
Enter your choice: 5
Exiting the program.

"""
Program List : L4
Program No : 2
Developed By : Harshit (XII-H)
Date : 16-08-2024
"""

import pickle

def Register():
with open("ACCOUNTS.DAT", "ab") as file:
Ano = int(input("Enter Account No: "))
Name = input("Enter Account Holder Name: ")
Balance = float(input("Enter Initial Balance: "))
if Balance >= 500:
account = [Ano, Name, Balance]
pickle.dump(account, file)
print("Account registered successfully.")
else:
print("Initial balance must be at least Rs 500.")

def Transact():
try:
accounts = []
with open("ACCOUNTS.DAT", "rb") as file:
while True:
try:
account = pickle.load(file)
accounts.append(account)
except EOFError:
break

Ano = int(input("Enter Account No for transaction: "))


found = False
for account in accounts:
if account[0] == Ano:
found = True
print(f"Current Balance: Rs {account[2]}")
trans_type = input("Enter 'D' to Deposit or 'W' to
Withdraw: ").upper()
amount = float(input("Enter the amount: "))

if trans_type == 'D':
account[2] += amount
print("Amount Deposited Successfully.")
elif trans_type == 'W':
if account[2] - amount >= 500:
account[2] -= amount
print("Amount Withdrawn Successfully.")
else:
print("Insufficient balance. Minimum balance of Rs
500 must be maintained.")
break

if not found:
print("Account not found.")
else:
with open("ACCOUNTS.DAT", "wb") as file:
for account in accounts:
pickle.dump(account, file)

except FileNotFoundError:
print("No records found. The file does not exist.")

def DisplayAll():
try:
with open("ACCOUNTS.DAT", "rb") as file:
print("All Account Holders:")
while True:
try:
account = pickle.load(file)
print(account)
except EOFError:
break
except FileNotFoundError:
print("No records found. The file does not exist.")

def BankBalance():
try:
total_balance = 0
with open("ACCOUNTS.DAT", "rb") as file:
while True:
try:
account = pickle.load(file)
total_balance += account[2]
except EOFError:
break
return total_balance
except FileNotFoundError:
print("No records found. The file does not exist.")
return 0

def menu():
while True:
print("\nMenu:")
print("1. Register new account holder")
print("2. Perform a transaction")
print("3. Display all account holders")
print("4. Calculate total bank balance")
print("5. Exit")
choice = int(input("Enter your choice: "))

if choice == 1:
Register()
elif choice == 2:
Transact()
elif choice == 3:
DisplayAll()
elif choice == 4:
total_balance = BankBalance()
print(f"Total Bank Balance: Rs {total_balance:.2f}")
elif choice == 5:
print("Exiting the program.")
break
else:
print("Invalid choice. Please try again.")

menu()
OUTPUT:
Menu:
1. Register new account holder
2. Perform a transaction
3. Display all account holders
4. Calculate total bank balance
5. Exit
Enter your choice: 1
Enter Account No: 234567
Enter Account Holder Name: Sumita Kumari Rath
Enter Initial Balance: 2000
Account registered successfully.

Menu:
1. Register new account holder
2. Perform a transaction
3. Display all account holders
4. Calculate total bank balance
5. Exit
Enter your choice: 1
Enter Account No: 546381
Enter Account Holder Name: Ananditaa Rath
Enter Initial Balance: 1000
Account registered successfully.

Menu:
1. Register new account holder
2. Perform a transaction
3. Display all account holders
4. Calculate total bank balance
5. Exit
Enter your choice: 2
Enter Account No for transaction: 234567
Current Balance: Rs 2000.0
Enter 'D' to Deposit or 'W' to Withdraw: W
Enter the amount: 1200
Amount Withdrawn Successfully.

Menu:
1. Register new account holder
2. Perform a transaction
3. Display all account holders
4. Calculate total bank balance
5. Exit
Enter your choice: 3
All Account Holders:
[234567, 'Sumita Kumari Rath', 800.0]
[546381, 'Ananditaa Rath', 1000.0]

Menu:
1. Register new account holder
2. Perform a transaction
3. Display all account holders
4. Calculate total bank balance
5. Exit
Enter your choice: 4
Total Bank Balance: Rs 1800.00

Menu:
1. Register new account holder
2. Perform a transaction
3. Display all account holders
4. Calculate total bank balance
5. Exit
Enter your choice: 5
Exiting the program.

[ ]
"""

Program List : L4

Program No : 3

Developed By : Harshit(XII-H)

Date : 17-08-2024

"""

import pickle

def Register():

with open("EMPLOYEES.DAT", "ab") as file:

Empno = int(input("Enter Employee No: "))

Ename = input("Enter Employee Name: ")

Department = input("Enter Department: ")

Salary = float(input("Enter Salary: "))


employee = [Empno, Ename, Department, Salary]

pickle.dump(employee, file)

print("Employee registered successfully.")

def GetAccounts():

try:

with open("EMPLOYEES.DAT", "rb") as file:

print("Employees in the ACCOUNTS department:")

while True:

try:

employee = pickle.load(file)

if employee[2].upper() == 'ACCOUNTS':

print(employee)

except EOFError:

break

except FileNotFoundError:

print("No records found. The file does not exist.")

def ShowAll():

try:

with open("EMPLOYEES.DAT", "rb") as file:

print("All Employees:")

while True:

try:

employee = pickle.load(file)

print(employee)

except EOFError:

break

except FileNotFoundError:
print("No records found. The file does not exist.")

def IncreaseSal():

try:

employees = []

with open("EMPLOYEES.DAT", "rb") as file:

while True:

try:

employee = pickle.load(file)

if employee[3] < 50000:

employee[3] += 10000

employees.append(employee)

except EOFError:

break

with open("EMPLOYEES.DAT", "wb") as file:

for employee in employees:

pickle.dump(employee, file)

print("Salaries updated successfully for employees earning less


than 50000.")

except FileNotFoundError:

print("No records found. The file does not exist.")

def menu():

Register()

GetAccounts()

ShowAll()

IncreaseSal()

ShowAll()

menu()
OUTPUT:
Enter Employee No: 1
Enter Employee Name: raju
Enter Department: abc
Enter Salary: 2000000
Employee registered successfully.
Employees in the ACCOUNTS department:
All Employees:
[1, 'raju', 'abc', 2000000.0]
Salaries updated successfully for employees earning less than 50000.
All Employees:
[1, 'raju', 'abc', 2000000.0]

"""
Program List : L4
Program No : 4
Developed By : Harshit (XII-H)
Date : 17-08-2024
"""

import pickle

def AddItem():
with open("ITEMS.DAT", "ab") as file:
Itemno = int(input("Enter Item No: "))
Iname = input("Enter Item Name: ")
Quantity = int(input("Enter Quantity: "))
Price = float(input("Enter Price: "))
item = [Itemno, Iname, Quantity, Price]
pickle.dump(item, file)
print("Item added successfully.")

def ShowItems(File):
try:
with open(File, "rb") as file:
print(f"Contents of {File}:")
while True:
try:
item = pickle.load(file)
print(item)
except EOFError:
break
except FileNotFoundError:
print(f"No records found. The file {File} does not exist.")

def CreateDemand():
try:
with open("ITEMS.DAT", "rb") as infile, open("LOWSTOCK.DAT", "wb")
as outfile:
while True:
try:
item = pickle.load(infile)
if item[2] < 10:
pickle.dump(item, outfile)
except EOFError:
break
print("LOWSTOCK.DAT file created successfully with items having
quantity less than 10.")
except FileNotFoundError:
print("No records found. The file ITEMS.DAT does not exist.")

def menu():
AddItem()
ShowItems('ITEMS.DAT')
CreateDemand()
ShowItems('LOWSTOCK.DAT')

menu()
"""
OUTPUT:
Enter Item No: 1
Enter Item Name: CHIPS
Enter Quantity: 20
Enter Price: 30
Item added successfully.
Contents of ITEMS.DAT:
[1, 'CHIPS', 20, 30.0]
LOWSTOCK.DAT file created successfully with items having quantity less
than 10.
Contents of LOWSTOCK.DAT:
"""

"""
Program List : L4
Program No : 5
Developed By : Harshit (XII-H)
Date : 17-08-2024
"""

import pickle
import datetime

def AddBook():
with open("BOOKS.DAT", "ab") as file:
Bno = int(input("Enter Book No: "))
Bname = input("Enter Book Name: ")
Author = input("Enter Author Name: ")
Price = float(input("Enter Price: "))
PurchaseDate = input("Enter Purchase Date (e.g., 15-Jun-2023): ")
book = [Bno, Bname, Author, Price, PurchaseDate]
pickle.dump(book, file)
print("Book added successfully.")

def ShowBooks():
try:
with open("BOOKS.DAT", "rb") as file:
print("Contents of BOOKS.DAT:")
while True:
try:
book = pickle.load(file)
print(book)
except EOFError:
break
except FileNotFoundError:
print("No records found. The file BOOKS.DAT does not exist.")
def DeleteOld():
cutoff_date = datetime.datetime.strptime("1-Jun-2024", "%d-%b-%Y")
try:
books = []
with open("BOOKS.DAT", "rb") as file:
while True:
try:
book = pickle.load(file)
purchase_date = datetime.datetime.strptime(book[4],
"%d-%b-%Y")
if purchase_date >= cutoff_date:
books.append(book)
except EOFError:
break

with open("BOOKS.DAT", "wb") as file:


for book in books:
pickle.dump(book, file)

print(f"Deleted books purchased before


{cutoff_date.strftime('%d-%b-%Y')}.")
except FileNotFoundError:
print("No records found. The file BOOKS.DAT does not exist.")

def menu():
AddBook()
ShowBooks()
DeleteOld()
ShowBooks()

menu()

"""OUTPUT:
Enter Book No: 1
Enter Book Name: gulliver's travels
Enter Author Name: jonathan swift
Enter Price: 130
Enter Purchase Date (e.g., 15-Jun-2023): 2-aug-2024
Book added successfully.
Contents of BOOKS.DAT:
[1, "gulliver's travels", 'jonathan swift', 130.0, '2-aug-2024']
Deleted books purchased before 01-Jun-2024.
Contents of BOOKS.DAT:
[1, "gulliver's travels", 'jonathan swift', 130.0, '2-aug-2024']
"""

L5 XII
"""
Program List : L5
Program No : 1
Developed By :Harshit (XII-H)
Date : 20-08-2024
"""
import csv

filename = "CANDIDATE.CSV"

def Enrol():
with open("CANDIDATE.CSV", mode="a", newline="") as file:
writer = csv.writer(file)
while True:
try:
candidate_no = int(input("Enter Candidate No: "))
cname = input("Enter Candidate Name: ")
score = float(input("Enter Score: "))
writer.writerow([candidate_no, cname, score])
print("Candidate details added successfully!")
except ValueError:
print("Invalid input. Please enter the correct data
type.")

more = input("Do you want to add another candidate? (y/n):


").lower()
if more != 'y':
break

def GetPass():
try:
with open("CANDIDATE.CSV", mode="r") as file:
reader = csv.reader(file)
next(reader)
print("\nCandidates who passed (Score >= 50):")
for row in reader:
if float(row[2]) >= 50:
print(f"Candidate No: {row[0]}, Name: {row[1]}, Score:
{row[2]}")
except FileNotFoundError:
print("CANDIDATE.CSV file not found.")
except ValueError:
print("Error reading score values. Ensure they are numeric.")

def ShowAll():
try:
with open("CANDIDATE.CSV", mode="r") as file:
reader = csv.reader(file)
next(reader)
print("\nAll Candidates:")
for row in reader:
print(f"Candidate No: {row[0]}, Name: {row[1]}, Score:
{row[2]}")
except FileNotFoundError:
print("CANDIDATE.CSV file not found.")
def AverageScore():
try:
with open("CANDIDATE.CSV", mode="r") as file:
reader = csv.reader(file)
next(reader)
scores = [float(row[2]) for row in reader]
if scores:
average = sum(scores) / len(scores)
return f"The average score of the candidates is:
{average:.2f}"
else:
return "No scores available to calculate average."
except FileNotFoundError:
return "CANDIDATE.CSV file not found."
except ValueError:
return "Error reading score values. Ensure they are numeric."

def menu():
while True:
print("\nMenu:")
print("a. Enroll a new candidate")
print("b. Show candidates who passed")
print("c. Show all candidates")
print("d. Show average score")
choice = input("Enter your choice: ")

if choice == 'a':
Enrol()
elif choice == 'b':
GetPass()
elif choice == 'c':
ShowAll()
elif choice == 'd':
print(AverageScore())
break
else:
print("Invalid choice. Please select a valid option.")

menu()
OUTPUT:
Menu:
a. Enroll a new candidate
b. Show candidates who passed
c. Show all candidates
d. Show average score
Enter your choice: a
Enter Candidate No: 1
Enter Candidate Name: neha
Enter Score: 92
Candidate details added successfully!
Do you want to add another candidate? (y/n): y
Enter Candidate No: 2
Enter Candidate Name: sindhu
Enter Score: 47
Candidate details added successfully!
Do you want to add another candidate? (y/n): y
Enter Candidate No: 3
Enter Candidate Name: naina
Enter Score: 100
Candidate details added successfully!
Do you want to add another candidate? (y/n): n

Menu:
a. Enroll a new candidate
b. Show candidates who passed
c. Show all candidates
d. Show average score
Enter your choice: b

Candidates who passed (Score >= 50):


Candidate No: 1, Name: neha, Score: 98.0
Candidate No: 2, Name: priya, Score: 97.0
Candidate No: 1, Name: neha, Score: 92.0
Candidate No: 3, Name: naina, Score: 100.0

Menu:
a. Enroll a new candidate
b. Show candidates who passed
c. Show all candidates
d. Show average score
Enter your choice: c

All Candidates:
Candidate No: 1, Name: neha, Score: 98.0
Candidate No: 2, Name: priya, Score: 97.0
Candidate No: 1, Name: neha, Score: 92.0
Candidate No: 2, Name: sindhu, Score: 47.0
Candidate No: 3, Name: naina, Score: 100.0

Menu:
a. Enroll a new candidate
b. Show candidates who passed
c. Show all candidates
d. Show average score
Enter your choice: d
The average score of the candidates is: 86.80

"""
Program List : L5
Program No : 2
Developed By : Harshit (XII-H)
Date : 20-08-2024
"""

import csv

def Register():
with open("ACCOUNTS.CSV", mode='a', newline='') as file:
writer = csv.writer(file)
try:
acno = int(input("Enter Account Number: "))
name = input("Enter Account Holder's Name: ")
balance = float(input("Enter Account Balance (minimum Rs 500):
"))
if balance < 500:
print("Balance must be at least Rs 500.")
return
writer.writerow([acno, name, balance])
print("Account registered successfully!")
except ValueError:
print("Invalid input. Please enter valid details.")

def Transact():
try:
acno = int(input("Enter Account Number: "))
with open("ACCOUNTS.CSV", mode='r') as file:
rows = list(csv.reader(file))
for row in rows:
if int(row[0]) == acno:
balance = float(row[2])
trans_type = input("Enter 'D' to deposit or 'W' to
withdraw: ").strip().lower()
amount = float(input("Enter amount: "))
if trans_type == 'deposit':
balance += amount
print(f"Amount deposited successfully! New
balance: {balance}")
elif trans_type == 'withdraw':
if balance - amount >= 500:
balance -= amount
print(f"Amount withdrawn successfully! New
balance: {balance}")
else:
print("Insufficient funds. Minimum balance of
Rs 500 must be maintained.")
return
else:
print("Invalid transaction type.")
return
row[2] = balance
break
else:
print("Account number not found.")
return
with open("ACCOUNTS.CSV", mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerows(rows)
except ValueError:
print("Invalid input. Please enter valid details.")

def DisplayAll():
try:
with open("ACCOUNTS.CSV", mode='r') as file:
reader = csv.reader(file)
print("Account Number | Name | Balance")
print("-------------------------------")
for row in reader:
print(f"{row[0]} | {row[1]} | Rs {row[2]}")
except FileNotFoundError:
print("No accounts found. Please register an account first.")

def BankBalance():
try:
total_balance = 0
with open("ACCOUNTS.CSV", mode='r') as file:
reader = csv.reader(file)
for row in reader:
total_balance += float(row[2])
return total_balance
except FileNotFoundError:
print("No accounts found. Please register an account first.")
return 0

def main():
while True:
print("\n--- Bank Management System ---")
print("1. Register a new account")
print("2. Perform a transaction")
print("3. Display all account holders")
print("4. Display total bank balance")
print("5. Exit")

choice = input("Enter your choice: ")


if choice == '1':
Register()
elif choice == '2':
Transact()
elif choice == '3':
DisplayAll()
elif choice == '4':
total_balance = BankBalance()
print(f"Total bank balance: Rs {total_balance}")
elif choice == '5':
print("Exiting the system.")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()

OUTPUT:
--- Bank Management System ---
1. Register a new account
2. Perform a transaction
3. Display all account holders
4. Display total bank balance
5. Exit
Enter your choice: 1
Enter Account Number: 123456
Enter Account Holder's Name: manoj arora
Enter Account Balance (minimum Rs 500): 300000
Account registered successfully!

--- Bank Management System ---


1. Register a new account
2. Perform a transaction
3. Display all account holders
4. Display total bank balance
5. Exit
Enter your choice: 1
Enter Account Number: 271220
Enter Account Holder's Name: naina rath
Enter Account Balance (minimum Rs 500): 140000
Account registered successfully!

--- Bank Management System ---


1. Register a new account
2. Perform a transaction
3. Display all account holders
4. Display total bank balance
5. Exit
Enter your choice: 2
Enter Account Number: 123456
Enter 'D' to deposit or 'W' to withdraw: D
Enter amount: 2000
Invalid transaction type.

--- Bank Management System ---


1. Register a new account
2. Perform a transaction
3. Display all account holders
4. Display total bank balance
5. Exit
Enter your choice: 3
Account Number | Name | Balance
-------------------------------
324900 | manoj arora | Rs 3000000.0
123456 | manoj arora | Rs 300000.0
271220 | naina rath | Rs 140000.0

--- Bank Management System ---


1. Register a new account
2. Perform a transaction
3. Display all account holders
4. Display total bank balance
5. Exit
Enter your choice: 4
Total bank balance: Rs 3440000.0

--- Bank Management System ---


1. Register a new account
2. Perform a transaction
3. Display all account holders
4. Display total bank balance
5. Exit
Enter your choice: 5
Exiting the system.

You might also like