0% found this document useful (0 votes)
7 views52 pages

Practical (1) Merged

Uploaded by

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

Practical (1) Merged

Uploaded by

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

PROGRAM NO.

1
Date:2/3/25

Define the following user-defined functions


a. GetStory(), to create a text file named STORY.TXT, which should contain
text lines entered by the user.
b. ViewStory(), to read and display the entire content of text fileSTORY.TXT on
the screen.
c. Words(), to read and display each word of the text fileSTORY.TXT
in different lines on the screen.

Write menu driven code to call the above functions

SOURCE CODE
def GetStory():
with open('Story.txt','w') as f:
while True:
line = input("Enter a line:")
f.write(line+'\n')
Choice = input("More?(Y/N)")
if Choice in 'nN':
break

def ViewStory():
try:
with open("Story.txt", "r") as f:
data = f.read()
print(data)
except
FileNotFoundError:
print("File not found")

def Words():
with open ("Story.txt","r") as f:
data = f.read().split()
for K in data:
print(K)

def menu():
while
True:
print("1. Create Story")
print("2. View Story")
print("3. Display
Words") print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
GetStory()
elif choice == '2':
ViewStory()
elif choice == '3':
Words()
elif choice == '4':
print("Exiting")
break
else:
print("Invalid choice")

OUTPUT

Enter choice: 1
This is my story.
It has two lines.

Enter choice: 2
This is my story.
It has two lines.

Enter choice: 3
This
is
my
story
. It
has
two
lines.
PROGRAM NO.2
Date: 5/3/25

Write a menu driven program to do the following functions:


a. CreateNotes() - to create a text file NOTES.TXT to have
text entered by the user.
b. CountAVD( )- to read the contents of the text file NOTESTXT and count
and print the number of Alphabets, Vowels and Digits present in the file
c. Show Notes()- to display the contents of text file NOTESTXT
d. RevText()- to read the contents of the text file NOTES TXT, and print reverse
of those lines which start with an alphabet 'T'
Write menu driven code to call the above functions

SOURCE CODE
def Createnotes():
with open('Notes.txt','w') as f:
while True:
line = input("Enter notes:")
f.write(line+'\n')
Choice = input("More?(Y/N)")
if Choice in 'nN':
break

def CountAVD():
with open("Notes.txt", "r") as f:
alphabets = vowels = digits = 0
data = f.read().split()
for K in data:
for A in K:
if A.isalpha():
alphabets += 1
if A in "AEIOUaeiou":
vowels += 1
elif
A.isdigit():
digits += 1
print("Alphabets:",alphabets)
print("Vowels:",vowels)
print("Digits:",digits)

def
Shownotes():
try:
with open("Notes.txt", "r") as
f: data = f.read()
print(data)
except
FileNotFoundError:
print("File not found")

def Revtext():
with open("Notes.txt", "r") as f:
data = f.readlines()
for K in data:
if K[0]=="T":
print(K[::-1])

def menu2():
while True:
print("1. Create Notes")
print("2. Count Alphabets,
Vowels, Digits") print("3. Show
Notes") print("4. Reverse 'T'
Lines") print("5. Exit")
choice = input("Enter your choice (1-5): ")

if choice == '1':
Createnotes()
elif choice == '2':
CountAVD()
elif choice == '3':
Shownotes()
elif choice == '4':
Revtext()
elif choice == '5':
print("Exiting")
break
else:
print("Invalid choice")

OUTPUT

Enter choice: 1
Enter lines (type 'END' to
stop): This is Test.
That is fine.

Enter choice: 2
Alphabets: 20
Vowels: 7
Digits: 0

Enter choice: 3
This is Test.
That is fine.

Enter choice: 4
.tseT si sihT
.enif si tahT
PROGRAM NO.3
Date: 9/3/25

Create a text file “story.txt” and then and then find and display the number of vowels,
consonants, uppercase, lowercase characters in the text file

SOURCE CODE
def Create():
with open('Story.txt','w') as f:
while True:
line = input("Enter a line:")
f.write(line+'\n')
Choice = input("More?(Y/N)")
if Choice in 'nN':
break

def
Count():
try:
vowels = consonants = uppercase = lowercase =
0 with open("story.txt", "r") as f:
for K in f:
for A
in K:
if
A.isalpha()
: if A in
'AEIOUaeiou':
vowels += 1
else:
consonants += 1
if A.isupper():
uppercase += 1
elif A.islower():
lowercase += 1
print("Vowels:", vowels)
print("Consonants:", consonants)
print("Uppercase letters:", uppercase)
print("Lowercase letters:", lowercase)
except
FileNotFoundError:
print("File not found")

OUTPUT
Vowels: 10
Consonants: 15
Uppercase: 2
Lowercase: 23
PROGRAM NO.4
Date: 12/3/25

Define functions to find sum of following series:


(i) X+X 2 + X 3 +............+ X N (use int N and X as parameters)
(ii) U+U2 2! + U3 3! +...............+ UN N! (use N and U as parameters)
(iii) X+2*X+3*X+....+N*X (use N and X as parameters)
(iv) 1 - 2! U2 + 3! U3 - 4! U4................+ N! UN (use int N and float U as parameters)
Call these functions in the main program and find results sum of various series with the help of
appropriate.

SOURCE CODE
def fun1(X,N):
Total = 0
for K in range (1,N+1):
Total = Total + (X**K)
print(Total)

def fun2(N,U):
Total = 0
for K in range(1,N+1):
F=1
for A in range(1,K+1):
F=F*A
Total = Total + ((U**K)/F)
print(Total)

def fun3(X,N):
Total = 0
for K in range(1,N+1):
Total += (K*X)

def
fun4(N,U):
Total = 1
Sign = -1
for K in range(2,N+1):
F=1
for A in range(1,K+1):
F*=A
Total += (F/(U**K))*(Sign**(K-
1)) print(Total)
OUTPUT

Sum of series 1: 120


Sum of series 2: 13.41
Sum of series 3: 150
Sum of series 4: -6.34
PROGRAM NO.5
Date: 17/3/25

Write a Python code with the following functions:


a. AddValues(L) - To add integer values entered by the user in the list L
b. DispValues(L) - To display values of L
c. SwapPair(L) - To re-arrange the content of L by swapping each pair
of adjacent neighbouring values
d. SwapHalf(L) - To re-arrange content of L by swapping first half of the
list with second half of the list
Write menu driven code to call the above functions

SOURCE CODE
L=[]
def
Addvalues():
while True:
Value= int(input("Enter value:"))
L.append(Value)
Choice = input("More?(Y/N)")
if Choice in 'Nn':
break
def Dispvalues():
print("Values:",L)

def SwapPair(L):
for k in range(0,len(L)-1,2):
L[k],L[k+1]=L[k+1],L[k]

def SwapHalf(L):
N = len(L)
if N%2==0:
for k in range(0,N//2,1): L[k],L[N//2+k]=L[N//2+k],L[k]
else:
for k in range(0,N//2,1): L[k],L[N//2+k+1]=L[N//2+k+1],L[k]

OUTPUT
Enter an integer :
1 More [Y/N] ? Y
Enter an integer :
2 More [Y/N] ? Y
Enter an integer :
3 More [Y/N] ? N
List is : [1, 2, 3]
List is : [2, 1, 3]
List is : [3, 1, 2]
PROGRAM NO.6
Date: 22/3/25

Write a menu driven program to do the following operations:


a. Factorial(n), to find and return factorial of a number n which is passed as parameter.
b. Reverse(n), to find and display the reverse of a number which is passed as a parameter.
c. IsPrime(n), to find that the given number is prime, composite or not
prime nor composite.
Write menu driven code to call the above functions

SOURCE CODE

def Factorial(n):
F=1
for K in range(1,n+1):
F=F*K
print(F)

def Reverse(n):
print(str(n)[::-1])

def
Isprime(n):
if n==1:
print(n,"is neither prime nor composite")
elif n>1:
for K in range(2,n):
if n%K==0:
print(n,"is
composite") break
else:
print(n,"is prime")

def menu3():
n=int(input("Enter
no.:")) while True:
print('''1. Factorial
2. Reverse
3. Is it prime?
4. Exit''')
choice = input("Enter your choice (1-4): ")

if choice == '1':
Factorial(n)
elif choice == '2':
Reverse(n)
elif choice == '3':
Isprime(n)
elif choice == '4':
print("Exiting")
break
else:
print("Invalid

choice") menu3()

OUTPUT

Enter choice: 1
Factorial: 120

Enter choice: 2
Reverse: 321

Enter choice: 3
Prime
PROGRAM NO.7
Date: 27/3/25

Write a Python code with the following functions performing mentioned operations on a
binary file “CANDIDATE.DAT” containing lists with [Candidateno of type int, Cname of
type string, Score of type float]
a) Enrol( ), to add details of new CANDIDATEs from the user and save
in “CANDIDATE.DAT”.
b) ShowAll( ), to display the entire content of “CANDIDATE.DAT”
c) GetPass( ), to read content from “CANDIDATE.DAT” and display details of
those candidates whose Score is>=50
d) AverageScore( ), to find and return the average of Score from
“CANDIDATE.DAT” Write menu driven code to call the above functions.

SOURCE CODE
import
pickle
def
Enrol():
with open("CANDIDATE.DAT","wb") as
f: L = []
while True:
Canno = int(input("Enter candidate number:"))
Cname = input("Enter name:")
Score = float(input("Enter Score:"))
L.append([Canno,Cname,Score])
Choice = input("More?(y/n):")
if Choice in 'nN':
break
pickle.dump(L,f)

def Showall():
with open("CANDIDATE.DAT","rb") as f:
data = pickle.load(f)
print("Candidate no.","Candidate Name","Score",sep="\t")
for K in data:
print(K[0],K[1],K[2],sep="\t \t")

def Getpass():
with open("CANDIDATE.DAT","rb") as f:
data = pickle.load(f)
for K in data:
if
K[2]>=50:
print("Candidate no.","Candidate Name","Score",sep="\t")
print(K[0],K[1],K[2],sep="\t \t")
else:
print("no record found")
def AverageScore():
with open("CANDIDATE.DAT","rb") as f:
data = pickle.load(f)
S = 0;N=0
for K in data: S
= S + K[2]
N +=1
print("Average score = ", S/N)

def menu4():
while True:
print('''1. Add detail
2. Display Content
3. Display Content of candidates whose score is more than 50
4. Average score
5. Exit''')
choice = input("Enter your choice (1-4): ")

if choice == '1':
Enrol()
elif choice == '2':
Showall()
elif choice == '3':
Getpass()
elif choice == '4':
AverageScore()
elif choice == '5':
print("Exiting")
break
else:
print("Invalid

choice") menu4()

OUTPUT

CandidateNo:
101 Name: Asha
Score: 67.5

All Candidates:
[101, 'Asha', 67.5]

Passed
Candidates: [101,
'Asha', 67.5]

Average Score: 67.5


PROGRAM NO.8
Date: 29/3/25

Write a Python code with the following functions performing mentioned


operations on a binary file “ACCOUNTS.DAT” containing lists with [Ano of
type int, Name of type string, Balance of type float]
a) Register( ), to add details of new account holders as entered by the user in the
binary file named ACCOUNTS.DAT.
b) DisplayAll( ) to display the details of all Account Holders from ACCOUNTS.DAT
c) Transact( ), to perform a transaction i.e. Deposit or Withdraw an Amount in an
Account Holders Balance whose Acno is entered by the user from ACCOUNTS.DAT.
Note: an Account Holder must always have a minimum Balance of Rs 500 in his/her
Account.
d) BankBalance() to find and return the sum of Balance of all the account
holders from ACCOUNTS.DAT
Write menu driven code to call the above functions.

SOURCE CODE
import pickle
def Register():
L=[]
with open("ACCOUNTS.DAT", "wb") as f:
while True:
Ano = int(input("Enter Account Number: "))
Name = input("Enter Name: ")
Balance = float(input("Enter Balance (min Rs.500): "))
L.append([Ano, Name, Balance])
Choice =
input("More?(y/n):") if
Choice in 'nN':
break
if Balance >= 500:
pickle.dump(L, f)
print("Account
Registered")
else:
print("Minimum Rs.500 required. Account not registered.\n")

def Displayall():
with open("ACCOUNTS.DAT","rb") as f:
data = pickle.load(f)
print("Account no.","Name "," Score",sep="\t")
for K in data:
print(K[0],K[1],K[2],sep="\t \t")

def Transact():
with open("ACCOUNTS.DAT","rb+") as f:
data = pickle.load(f)
Acno = int(input("Enter account no.:"))
print('1. Withdraw\n2. Deposit')
Choice = int(input("What do you want to do?(1 or 2):"))
if Choice == 1:
for K in data:
if K[0] == Acno:
Amount = int(input("How much money do you want to withdraw?:"))
K[2] = K[2] - Amount
print("New amount =", K[2])
else:
print("Account no. not found")
f.seek(0)
pickle.dump(data,f)
elif Choice == 2:
for K in data:
if K[0] == Acno:
Amount = int(input("How much money do you want to Deposit?:"))
K[2] = K[2] + Amount
print("New amount =", K[2])
else:
print("Account no. not found")
f.seek(0)
pickle.dump(data,f)

def BankBalance():
with open("ACCOUNTS.DAT","rb") as f:
data = pickle.load(f)
Sum = 0
for K in data:
Sum = Sum + K[2]
print(Sum)

def menu5():
while True:
print('''1. Register
2. Display
3. Transact
4. Bank Balance
5. Exit''')
choice = input("Enter your choice (1-4): ")

if choice == '1':
Register()
elif choice == '2':
Displayall()
elif choice == '3':
Transact()
elif choice == '4':
BankBalance()
elif choice == '5':
print("Exiting")
break
else:
print("Invalid

choice") menu5()

OUTPUT

Enter details:
101 Rahul 6000

All Accounts:
[101, 'Rahul',
6000]

Transaction: Deposit
Amount: 1000
Updated Balance: 7000
Total Balance: 7000
PROGRAM NO.9
Date: 2/4/25

Write a menu driven program to do the following operations on a binary file


EMPLOYEE.DAT:
a) Create( ) – Accept EMPNO, NAME and SALARY from user and then store in
binary file till user wants to store.
b) Display( ) – Show the information of all the employees in tabular form.
c) Search( ) – Display the information of an employee whose EMPNO is entered by
the user. If
EMPNO not found the display message “No Such Employee Exist”
d) Modify( ) – Change the Name and Salary of an employee whose EMPNO
is passed as parameter.
e) Delete( ) – Delete the information of an employee whose Name is entered by the user.
If Name
not found the display message “No Such Employee Exist”
Write menu driven code to call the above functions.

SOURCE CODE
import
pickle
def
Create():
with open("EMPLOYEE.DAT","wb") as f:
L = []
while True:
EMPNO = int(input("Enter employee number:"))
Name = input("Enter Name:")
Salary = float(input("Enter Salary:"))
L.append([EMPNO,Name,Salary])
Choice = input("More?(y/n):")
if Choice in 'nN':
break
pickle.dump(L,f)

def Display():
with open("EMPLOYEE.DAT","rb") as f:
data = pickle.load(f)
print("Employee no.","Employee name","Salary",sep="\
t") for K in data:
print(K[0],K[1],K[2],sep="\t \t")

def Search():
with open("EMPLOYEE.DAT","rb") as f:
data = pickle.load(f)
Eno=int(input("Enter employee
number:")) for K in data:
if K[0]==Eno:
print("Employee no.","Employee name","Salary",sep="\t")
print(K[0],K[1],K[2],sep="\t \t")
break
else:

print("No such employee exist")

def
Modify(emp):
L = []
with open("EMPLOYEE.DAT", "rb") as f:
while True:
K = pickle.load(f)
if K[0] == emp:
NAME = input("Enter new Name: ")
SALARY = input("Enter new Salary: ")
L.append([K[0], NAME, SALARY])
else:
L.append(K)

with open("EMPLOYEE.DAT", "wb") as f:


for K in L:
pickle.dump(K, f)

def Delete():
with open("EMPLOYEE.DAT","rb+") as f:
data = pickle.load(f)
L=[]
Name= input("Enter name:")
Found = 0
for K in
data:
if K[1] == Name:
print('Empno:',K[0],"Salary:",K[2])
Found = 1
else:
L.append(K)
if Found == 0:
print("No such employee exist")
with open("EMPLOYEE.DAT","wb") as f:
pickle.dump(L,f)

def menu6():
while True:
print('''1. Create
2. Display
3. Search
4. Modify
5. Delete
6. Exit''')
choice = input("Enter your choice (1-6): ")
if choice == '1':

Create()

elif choice == '2':


Display()
elif choice == '3':
Search()
elif choice == '4':
Modify()
elif choice == '5':
Delete()
elif choice == '6':
print("Exiting")
break
else:
print("Invalid”)

OUTPUT

All Employees:

101 Asha 50000

Search Result:

101 Asha 50000

After Modify:

101 Asha 55000

After Deletion:

No Such Employee Exist


PROGRAM NO.10
Date: 5/4/25

Write a menu driven program to do the following operations on a csv file


"MEMBER.CSV":
a) To add details of new members (Mno, Name, Fee, Type) in the csv file with the
content of the user.
b) To display the details of all the members from the csv file
c) To search for a member matching with Mno entered by the user and display the
details of the member from the csv file
d) To calculate and display the average Fee from the csv
file. Write menu driven code to call the above functions.

SOURCE CODE
import csv
def Add():
L=[]
with open("MEMBER.CSV","a",newline="") as f:
data = csv.writer(f,delimiter=',')
while True:
Mno = int(input("Enter Member number:"))
Name = input("Enter name:")
Fee = int(input("Enter fee:"))
Type = input("Enter type:")
L.append([Mno,Name,Fee,Type])
Choice = input("More?(y/n)")
if Choice in 'nN':
break
data.writerows(L)

def DisplayMembers():
with open("MEMBER.CSV", "r") as f:
data = csv.reader(f) print("Mno\
tName\tFee\tType")
for K in data:
print(K[0], "\t", K[1], "\t", K[2], "\t", K[3])

def SearchMember():
mno = input("Enter Member number: ")
found = 0
with open("MEMBER.CSV", "r") as f:
data = csv.reader(f)
for K in data:
if K[0] == mno: print("Mno\tName\tFee\
tType") print(K[0], "\t", K[1], "\t", K[2],
"\t", K[3])
found = 1
break
if found==0:
print("No such member.")

def AverageFee():
total = 0
count = 0
with open("MEMBER.CSV", "r") as f:
data = csv.reader(f)
for K in data:
total += int(K[2])
count += 1
if count > 0:
print("Average Fee:", total / count)
else:
print("No data")

def menu7():
while True:
print('''1. Add detail
2. Display detail
3. Search detail
4. Average fees
5. Exit''')
choice = input("Enter your choice (1-5): ")

if choice == '1':
Add()
elif choice == '2':
DisplayMembers()
elif choice == '3':
SearchMember()
elif choice == '4':
AverageFee
elif choice == '5':
print("Exiting")
break
else:
print("Invalid

choice")
OUTPUT

[101, 'Riya', 2500.0, 'Gold']

Average Fee: 2500.0


PROGRAM NO.11
Date: 7/4/25

Write a menu driven program to do the following operations on a csv file


"STOCK.CSV":
a) To add details of new items (INO, ITEM, PRICE, QTY) in the csv file with the
content of the user
b) To display the details of all the items along with stock value of each
item (PRICE*QTY) from the csv file
c) To search for a item matching with Ino entered by the user and then display the
details of the items from the csv file
d) To display all names of all items, whose name starts with "P" letter.
e) Copy all the items to a CSV file "REORDER.CSV" whose quantity is less than
10 in stock and then display the CSV file "REORDER.CSV".

Write menu driven code to call the above functions

SOURCE CODE

def AddItem():
with open("STOCK.CSV", "a", newline='') as f:
data = csv.writer(f)
while True:
ino = input("Enter Item Number: ")
item = input("Enter Item Name: ")
price = float(input("Enter Price: "))
qty = int(input("Enter Quantity: "))
data.writerow([ino, item, price, qty])
choice = input("Add more? (y/n): ")
if choice in 'nN':
break
print("Items
added")

def DisplayItems():
with open("STOCK.CSV", "r") as f:
data = csv.reader(f)
print("INO", "ITEM", "PRICE", "QTY", "STOCK VALUE", sep='\t')
for K in data:
stock = float(K[2]) * int(K[3])
print(K[0], K[1], K[2], K[3], stock, sep='\t')

def SearchItem():
ino = input("Enter Item number: ")
found = 0
with open("STOCK.CSV", "r") as f:
data = csv.reader(f)
for K in data:
if K[0] == ino:
print("INO", "ITEM", "PRICE", "QTY", sep='\t')
print(K[0], K[1], K[2], K[3], sep='\t')
found = 1
if found==0:
print("No such item found")

def DisplayPItems():
print("Items starting with
'P':")
with open("STOCK.CSV", "r") as f:
data = csv.reader(f)
for K in data:
if K[1].startswith("P") or K[1].startswith("p"):
print(K[1])

def Reorder():
with open("STOCK.CSV", "r") as f:
data = csv.reader(f)
L = []
for K in data:
if int(K[3]) < 10:
L.append(K)

with open("REORDER.CSV", "w", newline='') as f:


data = csv.writer(f)
data.writerows(L)

print("Items copied to REORDER.CSV are:")


with open("REORDER.CSV", "r") as f:
data =
csv.reader(f) for
K in data:
print(K)

def menu8():
while True:
print("1. Add Item")
print("2. Display Items with Stock Value")
print("3. Search")
print("4. Items Starting with 'P'")
print("5. Reorder")
print("6. Exit")
Choice = input("Enter your choice (1-6): ")
if Choice == '1':
AddItem()
elif Choice ==
'2':
DisplayItems()
elif Choice ==
'3':
SearchItem()
elif Choice ==
'4':
DisplayPItems()
elif Choice == '5':
Reorder()
elif Choice == '6':
break
else:
print("Invalid choice.")

OUTPUT

[101, 'Pen', 2000.0, 120]

Items starting with


P:
Pen, Pencil

REORDER:
[103, 'Pencil', 10, 9]
PROGRAM NO.12
Date: 10/4/25

Write a menu driven program to do the following operations on a csv file


"CADETS.CSV".
a) To add details of new cadets (CNO, NAME, GENDER, AGE, HEIGHT) in the
CSV file with the content of the user
b) To display the details of all the cadets from the CSV file
c) To display the detail of all the cadets whose gender is passed as parameter from
the CSV file
d) To Modify the Age and Height of cadet whose Candidate Number (Cno) is entered
by user.

Write menu driven code to call the above functions.

SOURCE CODE

import csv
def AddCadets():
with open("CADETS.CSV", "a", newline='') as f:
data = csv.writer(f)
while True:
CNO = input("Enter Cadet No: ")
NAME = input("Enter Name: ")
GENDER = input("Enter Gender (M/F): ")
AGE = input("Enter Age: ")
HEIGHT = input("Enter Height: ")
data.writerow([CNO, NAME, GENDER, AGE, HEIGHT])
choice = input("more? (y/n): ")
if choice in 'nN':
break

def DisplayAll():
with open("CADETS.CSV", "r") as f:
data = csv.reader(f)
print("CNO", "NAME", "GENDER", "AGE", "HEIGHT", sep='\t')
for K in data:
print(K[0], K[1], K[2], K[3], K[4], sep='\t')

def DisplayByGender(G):
with open("CADETS.CSV", "r") as f:
data = csv.reader(f)
print("CNO", "NAME", "GENDER", "AGE", "HEIGHT", sep='\t')
for K in data:
if K[2].upper() == G.upper():
print(K[0], K[1], K[2], K[3], K[4], sep='\t')

def ModifyCadet():
Cno = input("Enter Cno: ")
L = []
found = 0
with open("CADETS.CSV", "r") as f:
data = csv.reader(f)
for K in data:
if K[0] == Cno:
AGE = input("Enter new Age: ")
HEIGHT = input("Enter new Height: ")
L.append([K[0], K[1], K[2], AGE, HEIGHT])
found = 1
else:
L.append(K)
with open("CADETS.CSV", "w", newline='') as f:
data = csv.writer(f)
data.writerows(L)
if found==1:
print("Cadet record updated.")
else:
print("Cadet not found.")

def menu9():
while True:
print("1. Add")
print("2. Display All")
print("3. Display by gender")
print("4. Modify Age & Height")
print("5. Exit")
choice = input("Enter your choice (1-5): ")

if choice == '1':
AddCadets()
elif choice == '2':
DisplayAll()
elif choice == '3':
G = input("Enter Gender(M/F) ")
DisplayByGender(G)
elif choice == '4':
ModifyCadet()
elif choice == '5':
print("Exiting")
break
else:
print("Invalid choice")
OUTPUT

Cadets:
[101, 'Anu', 'F', 18, 5.4]

Gender: F
[101, 'Anu', 'F', 18, 5.4]

After Modify:
[101, 'Anu', 'F', 19, 5.5]
PROGRAM NO.13
Date: 13/4/25

Write a Python code with the following functions performing mentioned operations on a CSV
file “ACCOUNTS.CSV” containing lists with [Ano of type int, Name of type string, Balance of
type float]
a. Register(), to add details of new account holders as entered by the user in the CSV
file named ACCOUNTS.CSV.
b. DisplayAll( ) to display the details of all Account Holders from ACCOUNTS.CSV

Write menu driven code to call the above functions.

SOURCE CODE

import csv
def Register():
with open("ACCOUNTS.CSV", "a", newline="") as f:
data = csv.writer(f)
while True:
Ano = int(input("Enter Account Number: "))
Name = input("Enter Name: ")
Balance = float(input("Enter Balance: "))
data.writerow([Ano, Name, Balance])
choice = input("More?(y/n): ")
if choice in 'nN':
break

def DisplayAll():
print("Ano", "Name", "Balance", sep='\t')
with open("ACCOUNTS.CSV", "r", newline="") as f:
data = csv.reader(f)
for K in data:
print(K[0], K[1], K[2], sep='\t')

def
menu10():
while True:
print("1.
Register")
print("2. Display")
print("3. Exit")
choice = input("Enter your choice: ")

if choice == '1':
Register()
elif choice == '2':
DisplayAll()
elif choice == '3':
break
else:
print("Invalid choice")

OUTPUT

[201, 'Karan', 12000]


PROGRAM NO.14
DATE: 16/4/25

You have a stack named BooksStack that contains records of books. Each book record is
represented as a list containing book_title, author_name, and publication_year.
Write the following user-defined functions in Python to perform the specified operations
on the stack BooksStack:
(a) push_book(BooksStack, new_book): This function takes the stack
BooksStack and a new book record new_book as arguments and pushes the
new book record onto the stack.
(b) pop_book(BooksStack): This function pops the topmost book record
from the stack and returns it. If the stack is already empty, the function
should display "Underflow".
(c) peep(BookStack): This function displays the topmost element of the
stack without deleting it. If the stack is empty, the function should display
'None'.
Write menu driven code to call the above functions.

SOURCE CODE
def push_book(BooksStack, new_ book):
BooksStack.append(new_book)

def pop_book(BooksStack): if
len(BooksStack) == 0:
print("Underflow")
else:
return BooksStack.pop()

def peep(BooksStack):
if len(BooksStack) == 0:
print("None")
else:
print("Top Book:", BooksStack[-

1]) BooksStack = []

while True:
print("\n1. Push Book")
print("2. Pop Book")
print("3. Peep Book")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
title = input("Enter Book Title: ") author
= input("Enter Author Name: ")
year = input("Enter Publication Year: ") new_book =
[title, author, year] push_book(BooksStack,
new_book)

elif choice == '2':


book = pop_book(BooksStack) if
book:
print("Popped Book:", book)

elif choice == '3':


peep(BooksStack)

elif choice == '4':


break

else:
print("Invalid choice")

OUTPUT

Enter your choice: 1


Enter Book Title: The Alchemist
Enter Author Name: Paulo Coelho
Enter Publication Year: 1988
PROGRAM NO.15
DATE: 17/4/25

Given a Dictionary Stu_dict containing marks of students for three test-series in the form
Stu_ID:(TS1, TS2, TS3) as key-value pairs.
Write a Python program with the following user-defined functions to perform the
specified operations on a stack named Stu_Stk
(i) Push_elements(Stu_Stk, Stu_dict) : It allows pushing IDs of
those students, from the dictionary Stu_dict into the stack Stu_Stk, who
have scored more than or equal to 80 marks in the TS3 Test.
(ii) Pop_elements(Stu_Stk): It removes all elements present inside
the stack in LIFO order and print them. Also, the function displays
'Stack Empty' when there are no elements in the stack.
(iii) Display(Stu_Stk) : It displays all the elements of stack
Stu_Stk. Write menu driven code to call the above functions.

SOURCE CODE

def Push_elements(Stu_Stk, Stu_dict): for


ID in Stu_dict:
if Stu_dict[ID][2] >= 80: Stu_Stk.append(ID)

def Pop_elements(Stu_Stk): if
not Stu_Stk:
print("Stack
Empty") else:
while Stu_Stk:
print("Pop:", Stu_Stk.pop())

def
Display(Stu_Stk):
if not Stu_Stk:
print("Stack
Empty") else:
print("Stack Elements:", Stu_Stk)

Stu_dict = {
101: (75, 88, 82),
102: (90, 78, 79),
103: (85, 89, 91),
104: (60, 72, 84),
105: (78, 80, 76)}
Stu_Stk = []
while True:
print("\n1. Push Elements")
print("2. Pop Elements")
print("3. Display Stack")
print("4. Exit")
ch = input("Enter your choice: ")

if ch == '1':
Push_elements(Stu_Stk,
Stu_dict) elif ch == '2':
Pop_elements(Stu_Stk)
elif ch == '3':
Display(Stu_Stk)
elif ch == '4':
break
else:
print("Invalid choice")

OUTPUT

After option 1 (Push):


Stack Elements: [101, 103, 104]

After option 2 (Pop):


Pop: 104
Pop: 103
Pop: 101

After another Pop:


Stack Empty
PROGRAM NO.16

DATE: 19/4/25

A list, NList contains the following record as list elements: [City, Country, distance from
Delhi] Each of these records are nested together to form a nested list.
Write the following user defined functions in Python to perform the specified operations
on the stack named travel.
(i) Push_element(NList): It takes the nested list as an argument and
pushes a list object containing the name of the city and country, which
are not in India and distance is less than 3500 km from Delhi.
(ii) Pop_element( ): It pops the objects from the stack and displays them.
Also, the function should display “Stack Empty” when there are no elements
in the stack.
(iii) Display( ) : It displays all the elements of stack
travel. Write menu driven code to call the above functions.

SOURCE CODE

def Push_element(NList): for


record in NList:
if record[1]== "India" and record[2] < 3500:
travel.append([record[0], record[1]])

def Pop_element(): if
not travel:
print("Stack
Empty") else:
while travel:
print("Pop:",
travel.pop()) def Display():
if not travel:
print("Stack
Empty")
else:
print("Stack Elements:", travel)

NList = [
["Kathmandu", "Nepal", 1000],
["Colombo", "Sri Lanka", 3400],
["Paris", "France", 7000],
["Dhaka", "Bangladesh", 1500],
["Mumbai", "India", 1400],
["Dubai", "UAE", 2800]]
travel = []
while
True:
print("\n1. Push Element")
print("2. Pop Element") print("3.
Display Stack") print("4. Exit")
ch = input("Enter your choice: ")

if ch == '1':
Push_element(NList)
elif ch == '2':
Pop_element()
elif ch == '3':
Display()
elif ch == '4':
break
else:
print("Invalid choice")

OUTPUT

Pop: ['Dubai', 'UAE']


Pop: ['Dhaka', 'Bangladesh']
Pop: ['Colombo', 'Sri Lanka']
Pop: ['Kathmandu', 'Nepal']
PROGRAM NO.18

DATE: 4/5/25

Sartaj has created a table named Student in MYSQL database,


SCHOOL:
RNO(Roll number )- integer, NAME(Name) - string, DOB (Date of birth) –
Date, FEE – float
Assume the following for Python-Database connectivity:
Host: localhost, User: root, Password: Sgs
Write user defined functions to do the following operations:
a) Display the records of students whose fee is more than 5000.
b) Increase the Fee of all students by 10%.

SOURCE CODE

import
mysql.connector
def connect():
return mysql.connector.connect(
host="localhost",
user="root",
password="SgsWrite",
database="SCHOOL")

def
displaystudents():
try:
con = connect_db()
cursor = con.cursor()
query = "select * from student where fee> 5000"
cursor.execute(query)
records cursor.fetchall()
print("Students with Fee > 5000:")
for row in records:
print(f"RNO: {row[0]}, NAME: {row[1]}, DOB: {row[2]}, FEE: {row[3]}")
cursor.close()
con.close()
except Exception as e:
print("Error:", e)

def
increase_fee():
try:
con = connect_db()
cursor = con.cursor()
query = "update student set fee = fee * 1.10"
cursor.execute(query)
con.commit()
print(f"{cursor.rowcount} records updated.")
cursor.close()
con.close()
except Exception as e:
print("Error:", e)

OUTPUT
BEFORE FEE UPDATE
Students with Fee > 5000:
RNO: 2, NAME: Riya, DOB: 2005-08-21, FEE: 5200
RNO: 3, NAME: Sartaj, DOB: 2006-01-30, FEE: 6000
RNO: 5, NAME: Priya, DOB: 2006-03-25, FEE: 5100

AFTER FEE UPDATE


Students with Fee > 5000:
RNO: 2, NAME: Riya, DOB: 2005-08-21, FEE: 5720
RNO: 3, NAME: Sartaj, DOB: 2006-01-30, FEE: 6600
RNO: 5, NAME: Priya, DOB: 2006-03-25, FEE: 5610

RNO NAME DOB FEE

1 Aman 2006-05-14 4950

2 Riya 2005-08-21 5720

3 Sartaj 2006-01-30 6600

4 Karan 2005-11-12 3300

5 Priya 2006-03-25 5610


PROGRAM 19
DATE: 7/5/25

Write SQL commands for the following:


(i.) To create a table TEACHER with the following Columns:
TCODE INT(3) Primary Key
TEACHER NAME VARCHAR(25)
STREAM VARCHAR(15)
BASIC DECIMAL(8,2)
DATE OF JOINING DATE
ii. To insert the following rows in the table TEACHER
Table: TEACHER
TCODE TEACHER NAME STREAM BASIC DATE OF
JOINING
101 Ananya Murty Science 18000 1990-01-23
202 Kirti Khaneja Humanities 28000 1978-12-12
103 Adil Mehra Science 8000 2001-02-14
305 Nishiya Goel Commerce 12000 1997-01-01
203 Shubh Pandit Humanities 22000 1985-03-19
109 Naina Science 20000 1994-07-17
iii. To create a table STUDENT with the following Columns:
SCODE INT(3) Primary Key
NAME VARCHAR(25)
TCODE INT(3) reference key from Teacher table
AGG DECIMAL(5,1)
iv. To insert the following rows in the table STUDENT:
Table: STUDENT
SCODE NAME TCODE AGG
2 Nabi Ahmad 101 91
1 Ravi Sahai 305 84
5 Vibhuti 203 67
4 Nazneen 103 89
3 Aryana 202 37
6 Jonathan 305 45
v. To display the complete contents of the table TEACHER.
vi. To display details of those Teachers whose date of joining is from 1st of Jan 1978(‘1978-01-01’) to 30th
of November 1992 (‘1992-11-30’ - including both the days)
vii. To display the contents of the table STUDENT in descending order of AGG.
viii. To display NAME and SCODE of all the students who are taught by teachers having code numbers
101 and 203
ix. To display income tax amount from the table TEACHER by computing income tax as 25% of BASIC.
x. To replace the value of column AGG with 82 where NAME is Ravi Sahai in the table STUDENT
xi. To delete all the records from the table STUDENT where AGG is below 40.
xii. To change the STREAM of the teacher whose name is Ananya Murty to 'Humanities' and her BASIC to
21000.
xiii. To add a column called GRADE in the table STUDENT to accommodate one character.
xiv. To replace the column GRADE with 'A' in the table STUDENT whose AGG>=70
xv. To replace the column GRADE with 'B' in the table STUDENT whose AGG>=40 and AGG
SOURCE CODE AND OUTPUT

CREATE TABLE TEACHER (


TCODE INT(3) PRIMARY KEY,
`TEACHER NAME` VARCHAR(25),
STREAM VARCHAR(15),
BASIC DECIMAL(8,2),
`DATE OF JOINING` DATE
);

INSERT INTO TEACHER VALUES


(101, 'Ananya Murty', 'Science', 18000, '1990-01-23'),
(202, 'Kirti Khaneja', 'Humanities', 28000, '1978-12-12'),
(103, 'Adil Mehra', 'Science', 8000, '2001-02-14'),
(305, 'Nishiya Goel', 'Commerce', 12000, '1997-01-01'),
(203, 'Shubh Pandit', 'Humanities', 22000, '1985-03-19'),
(109, 'Naina', 'Science', 20000, '1994-07-17');
SELECT * FROM TEACHER;

CREATE TABLE STUDENT (


SCODE INT(3) PRIMARY KEY,
NAME VARCHAR(25),
TCODE INT(3),
AGG DECIMAL(5,1),
FOREIGN KEY (TCODE) REFERENCES TEACHER(TCODE)
);
INSERT INTO STUDENT VALUES
(2, 'Nabi Ahmad', 101, 91),
(1, 'Ravi Sahai', 305, 84),
(5, 'Vibhuti', 203, 67),
(4, 'Nazneen', 103, 89),
(3, 'Aryana', 202, 37),
(6, 'Jonathan', 305, 45);
SELECT * FROM STUDENT;

SELECT * FROM TEACHER


WHERE `DATE OF JOINING` BETWEEN '1978-01-01' AND '1992-11-30';

SELECT * FROM STUDENT ORDER BY AGG DESC;


SELECT NAME, SCODE FROM STUDENT WHERE TCODE IN (101, 203);
SELECT `TEACHER NAME`, BASIC, BASIC * 0.25 AS `INCOME TAX` FROM TEACHER;
UPDATE STUDENT SET AGG = 82 WHERE NAME = 'Ravi Sahai';

SELECT * FROM STUDENT WHERE NAME = 'Ravi Sahai';


DELETE FROM STUDENT WHERE AGG < 40;

SELECT * FROM STUDENT;


UPDATE TEACHER SET STREAM = 'Humanities', BASIC = 21000
WHERE `TEACHER NAME` = 'Ananya Murty';
SELECT * FROM TEACHER WHERE `TEACHER NAME` = 'Ananya Murty';
ALTER TABLE STUDENT ADD GRADE CHAR(1);
UPDATE STUDENT SET GRADE = 'A' WHERE AGG >= 70;
UPDATE STUDENT SET GRADE = 'B' WHERE AGG >= 40 AND AGG < 70;
SELECT * FROM STUDENT;
PROGRAM 20
DATE: 17/5/25

Table: SUPPLIER
SUPCODE SNAME CITY
S01 GET ALL INC KOLKATA S02
EASY MARKET CORP DELHI S03 DIGI
BUSY GROUP CHENNAI
Table: PRODUCT
PID PNAME QTY PRICE COMPANY SUPCODE
101 DIGITAL CAMERA 14X 120 12000 RENIX S01 102
DIGITAL PAD 11i 100 2200 DIGI POP S02 103 PEN DRIVE
16 GB 500 1100 STOREKING S01 104 LED SCREEN 32
70 28000 DISPEXPERTS S02 105 CAR GPS SYSTEM 60
12000 MOVEON S03
1. Create Products and suppliers tables, where SUPCODE is foreign key..
2. To display the details of all the products in the ascending order of the product names (i.e., PNAME).
3. To display the product name and the price of all those products, whose price is in the range of 10,000
and 15,000 (both values inclusive).
4. To display the names of those suppliers, who are either from DELHI or from CHENNAI.
5. To display the names of the companies and the products in the descending order of the company names.

SOURCE CODE

CREATE TABLE SUPPLIER (


SUPCODE VARCHAR(4) PRIMARY KEY,
SNAME VARCHAR(50),
CITY VARCHAR(30)
);

CREATE TABLE PRODUCT (


PID INT PRIMARY KEY,
PNAME VARCHAR(50),
QTY INT,
PRICE DECIMAL(10, 2),
COMPANY VARCHAR(40),
SUPCODE VARCHAR(4),
FOREIGN KEY (SUPCODE) REFERENCES SUPPLIER(SUPCODE)
);
-- SUPPLIER Table
INSERT INTO SUPPLIER VALUES
('S01', 'GET ALL INC', 'KOLKATA'),
('S02', 'EASY MARKET CORP', 'DELHI'),
('S03', 'DIGI BUSY GROUP', 'CHENNAI');

-- PRODUCT Table
INSERT INTO PRODUCT VALUES
(101, 'DIGITAL CAMERA 14X', 120, 12000, 'RENIX', 'S01'),
(102, 'DIGITAL PAD 11i', 100, 2200, 'DIGI POP', 'S02'),
(103, 'PEN DRIVE 16 GB', 500, 1100, 'STOREKING', 'S01'),
(104, 'LED SCREEN 32', 70, 28000, 'DISPEXPERTS', 'S02'),
(105, 'CAR GPS SYSTEM', 60, 12000, 'MOVEON', 'S03');
SELECT * FROM PRODUCT
ORDER BY PNAME ASC;

You might also like