Program 1
Program 1
SOURCE CODE
def ViewStory():
try:
with open('STORY.TXT','r') as f:
data= f.read()
print(data)
except FileNotFoundError:
print("No such file exists")
def Words():
try:
with open('STORY.TXT','r') as f:
for line in f:
words=line.split()
for w in words:
print(w)
except FileNotFoundError:
print("No such file exists")
while True:
print(" 1.Enter Text \n 2.View Data \n 3.View Data in different lines \n 4.Exit ")
Choice= int(input("Enter choice : "))
if Choice == 1:
GetStory()
elif Choice == 2:
ViewStory()
elif Choice == 3:
Words()
elif Choice == 4:
print("Exiting the program ")
break
else:
print("Invalid choice.")
OUTPUT
1.Enter Text
2.View Data
4.Exit
Enter choice : 1
More Y/N ?N
1.Enter Text
2.View Data
4.Exit
Enter choice : 2
Kunjal Sahay
1.Enter Text
2.View Data
4.Exit
Enter choice : 3
Kunjal
Sahay
1.Enter Text
2.View Data
4.Exit
Enter choice : 4
b. CountAVD( )- to read the contents of the text file NOTESTXT and count andprint the number of Alphabets,
Vowelsand Digits present in the file
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():
while True:
f.write(Text + '\n')
if Choice in 'Nn':
break
def CountAVD():
try:
D=0
V=0
A=0
data = f.read()
for k in data:
if k.isalpha():
if k in 'AEIOUaeiou':
V += 1
else:
A += 1
elif k.isdigit():
D += 1
print("Number of Alphabets:", A)
print("Number of Vowels:", V)
print("Number of Digits:", D)
except FileNotFoundError:
def ShowNotes():
try:
with open('NOTES.TXT','r') as f:
data= f.read()
print(data)
except FileNotFoundError:
def RevText():
try:
for line in f:
if line.strip().startswith('T'):
print(line.strip()[::-1])
except FileNotFoundError:
while True:
print("5. Exit")
if choice == '1':
CreateNotes()
elif choice == '2':
CountAVD()
ShowNotes()
RevText()
break
else:
print("Invalid choice.")
OUTPUT
1. Create Notes
3. Show Notes
5. Exit
More Y/N ?Y
More Y/N ?Y
More Y/N ?N
1. Create Notes
3. Show Notes
5. Exit
Number of Vowels: 20
Number of Digits: 1
1. Create Notes
3. Show Notes
5. Exit
Computer Science
Today is Monday
1. Create Notes
3. Show Notes
5. Exit
yadnoM si yadoT
1. Create Notes
3. Show Notes
5. Exit
Exiting program.
PROGRAM 3
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():
text = input("Enter text: ")
with open('story.txt', 'w') as f:
f.write(text)
V=0;C=0;L=0;U=0
with open('story.txt', 'r') as f:
data = f.read()
for ch in data:
if ch.isalpha():
if ch in 'AEIOUaeiou':
V += 1
else:
C += 1
if ch.islower():
L += 1
elif ch.isupper():
U += 1
print("Vowels:", V)
print("Consonants:", C)
print("Lowercase letters:", L)
print("Uppercase letters:", U)
Create()
OUTPUT
Enter text: There are 30 days and 4 weeks in the month of NOVEMBER
Vowels: 15
Consonants: 25
Lowercase letters: 31
Uppercase letters: 9
PROGRAM 4
Define functions to find sum of following series:
Call these functions in the main program and find results sum of various series
SOURCE CODE
S=0
for k in range(1,N+1,1):
S=S+(X**k)
print("Sum :" ,S )
S=0
S += i * X
print("Sum : ", S)
S=0
S += i * X
print("Sum : ", S)
U = int(input("Enter Number: "))
S=1
sign = -1
power = 1
for a in range(i):
power *= U
f=1
f *= j
S += sign * f * power
sign *= -1
print("SUM : ", S)
OUTPUT
Enter Number : 10
Sum : 111110
Enter Numerator : 1
Sum : 1.7166666666666668
Enter Number: 1
Sum : 5050
Enter Number: 5
SUM : 719332942898985
PROGRAM 5
5 Write a Python code with the following functions:
d. SwapHalf(L) - To re-arrange content of L by swapping firsthalf of the list with second half of the list
SOURCE CODE
def AddValues(L):
while True:
try:
value = int(input("Enter integer : "))
L.append(value)
except ValueError:
print("Please enter a valid integer.")
continue
choice = input("Do you want to add another value? (Y/n): ")
if choice in 'nN':
break
mylist = []
AddValues(mylist)
print("Final List:", mylist)
def DispValue():
L = []
while True:
V = input("Value: ")
L.append(V)
C = input("More? (Y/n): ")
if C in 'Nn':
break
print("Values in the list:")
for item in L:
print(item)
DispValue()
def SwapPair(L):
for i in range(0, len(L) - 1, 2):
L[i], L[i + 1] = L[i + 1], L[i]
def SwapHalf(L):
n = len(L)
mid = n // 2
if n % 2 == 0:
L[:] = L[mid:] + L[:mid]
else:
L[:] = L[mid+1:] + [L[mid]] + L[:mid]
OUTPUT
Enter integer : 10
Enter integer : 20
Value: 10
More? (Y/n): y
Value: 90
More? (Y/n): y
Value: 30
More? (Y/n): n
10
90
30
c. IsPrime(n), to find that the given number is prime, compositeor not prime nor composite.
SOURCE CODE
def Factorial(n):
fact = 1
for i in range(2, n + 1):
fact *= i
return fact
def Reverse(n):
rev = 0
while n > 0:
rev = rev * 10 + n % 10
n //= 10
print("Reversed number:", rev)
def IsPrime(n):
if n <= 1:
print("Not prime nor composite")
return
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
print("Composite number")
return
print("Prime number")
while True:
print("1. Factorial")
print("2. Reverse")
print("3. Check Prime")
print("4. Exit")
choice = input("Enter your choice : ")
if choice == '1':
n = int(input("Enter a number: "))
print("Factorial:", Factorial(n))
elif choice == '2':
n = int(input("Enter a number: "))
Reverse(n)
elif choice == '3':
n = int(input("Enter a number: "))
IsPrime(n)
elif choice == '4':
print("Exiting program.")
break
else:
print("Invalid choice. Try again.")
OUTPUT
1. Factorial
2. Reverse
3. Check Prime
4. Exit
Enter your choice : 1
Enter a number: 10
Factorial: 3628800
1. Factorial
2. Reverse
3. Check Prime
4. Exit
Enter your choice : 2
Enter a number: 48
Enter your choice : 3
Enter a number: 71
Prime number
1. Factorial
2. Reverse
3. Check Prime
4. Exit
Enter your choice : 4
Exiting program.
PROGRAM 7
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():
data = []
while True:
if choice in 'Nn':
break
pickle.dump(data, f)
import pickle
def ShowAll( ):
try:
with open('CANDIDATE.DAT','rb') as f:
data= pickle.load(f)
for k in data:
except FileNotFoundError:
import pickle
def GetPass( ):
with open('CANDIDATE.DAT','rb') as f:
data= pickle.load(f)
for k in data:
if k[2]>=50:
print(k[0], k[1], k[2] , sep='\t' )
import pickle
def AverageScore():
total = 0
count = 0
with open('CANDIDATE.DAT', 'rb') as f:
data = pickle.load(f)
for k in data:
total += k[2]
count += 1
if count > 0:
print("Average Score =", total / count)
else:
print("No records found.")
while True:
print("1. Enrol Candidates")
print("2. Show All Candidates")
print("3. Show Passed Candidates (Score >= 50)")
print("4. Show Average Score")
print("5. Exit")
choice = input("Enter your choice : ")
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")
OUTPUT
1. Enrol Candidates
2. Show All Candidates
3. Show Passed Candidates (Score >= 50)
4. Show Average Score
5. Exit
Enter your choice : 1
Enter Candidateno: 1
Enter Cname: Kunjal
Enter Score: 80
More? (Y/N): y
Enter Candidateno: 2
Enter Cname: Aayushi
Enter Score: 90
More? (Y/N): y
Enter Candidateno: 3
Enter Cname: Ashlie
Enter Score: 45
More? (Y/N): n
1. Enrol Candidates
2. Show All Candidates
3. Show Passed Candidates (Score >= 50)
4. Show Average Score
5. Exit
Enter your choice : 2
Candidaten Cname Score
1 Kunjal 80.0
2 Aayushi 90.0
3 Ashlie 45.0
1. Enrol Candidates
2. Show All Candidates
3. Show Passed Candidates (Score >= 50)
4. Show Average Score
5. Exit
Enter your choice : 3
1 Kunjal 80.0
2 Aayushi 90.0
1. Enrol Candidates
2. Show All Candidates
3. Show Passed Candidates (Score >= 50)
4. Show Average Score
5. Exit
Enter your choice : 4
Average Score = 71.66666666666667
1. Enrol Candidates
2. Show All Candidates
3. Show Passed Candidates (Score >= 50)
4. Show Average Score
5. Exit
Enter your choice : 5
Exiting
PROGRAM 8
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.
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
SOURCE CODE
import pickle
def Register( ):
with open('ACCOUNTS.DAT', 'wb') as f:
data = []
while True:
Ano = int(input("Enter Ano : "))
Name = input("Enter Name : ")
Balance = float(input("Enter Balance : "))
data.append([Ano, Name, Balance])
choice = input("More? (Y/N): ")
if choice in 'Nn':
break
pickle.dump(data, f)
import pickle
def DisplayAll( ):
try:
with open('ACCOUNTS.DAT','rb') as f:
data= pickle.load(f)
print('Ano', 'Name', 'Balance', sep='\t' )
for k in data:
print(k[0], k[1], k[2] , sep='\t' )
except FileNotFoundError:
print("No such file exists")
import pickle
def Transact( ):
with open('ACCOUNTS.DAT', 'rb+') as f:
data=pickle.load(f)
while True:
Ano = int(input("Enter Ano : "))
dep=input("enter D/W :")
amount=int(input("enter:"))
for k in data:
if(k[0]==Ano):
if(dep=='E'):
if(k[2]-amount>=500):
k[2]=k[2]-amount
else:
print("low balance")
else:
k[2]+=amount
choice = input("More? (Y/N): ")
if choice in 'Nn':
break
f.seek(0)
pickle.dump(data, f)
import pickle
def Bankbalance( ):
with open('ACCOUNTS.DAT', 'rb') as f:
data=pickle.load(f)
t=0
for k in data:
t+=k[2]
print(t)
while True:
print("1. Add Account Holders")
print("2. Display details of all Account Holders ")
print("3. Perform a transaction )")
print("4. Show sum of Balance ")
print("5. Exit")
choice = input("Enter your choice : ")
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")
OUTPUT
1. Add Account Holders
3. Perform a transaction )
5. Exit
Enter Ano : 1
More? (Y/N): y
Enter Ano : 2
More? (Y/N): n
3. Perform a transaction )
5. Exit
Enter your choice : 2
1 Kunjal 2000.0
2 Aayushi 1500.0
3. Perform a transaction )
5. Exit
Enter Ano : 1
enter D/W :W
enter:500
More? (Y/N): y
Enter Ano : 2
enter D/W :D
enter:500
More? (Y/N): n
3. Perform a transaction )
5. Exit
4500.0
3. Perform a transaction )
5. Exit
Exiting
PROGRAM 9
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.
c) Search( ) – Display the information of employee whose EMPNO is entered by user. If EMPNO not found the
display message “No Such Employee Exist”
d) Modify( ) – Change the Name and Salary of employee whose EMPNO is passed as parameter.
e) Delete( ) – Delete the information of employee whose Name is entered by user. If Name not found the display
message “No Such Employee Exist”
SOURCE CODE
import pickle
def Create( ) :
with open('EMPLOYEE.DAT', 'wb') as f:
data = []
while True:
EMPNO = int(input("Enter EMPNO: "))
NAME = input("Enter NAME : ")
SALARY = int(input("Enter SALARY: "))
data.append([EMPNO, NAME , SALARY])
choice = input("More? (Y/N): ")
if choice in 'Nn':
break
pickle.dump(data, f)
import pickle
def Display( ) :
try:
with open('EMPLOYEE.DAT','rb') as f:
data= pickle.load(f)
print("EMPNO", "NAME" , "SALARY", sep='\t' )
for k in data:
print(k[0], k[1], k[2] , sep='\t' )
except FileNotFoundError:
print("No such file exists")
import pickle
def Search():
EMPNO = int(input("Enter EMPNO: "))
with open('EMPLOYEE.DAT', 'rb') as f:
data = pickle.load(f)
for k in data:
if k[0] == EMPNO:
print('Name:', k[1], 'SALARY:', k[2], sep='\t')
break
else:
print("Employee not found.")
import pickle
def Modify():
with open('EMPLOYEE.DAT', 'rb+') as f:
data = pickle.load(f)
while True:
EMPNO = int(input("Enter EMPNO : "))
for i in range(len(data)):
if data[i][0] == EMPNO:
NAME = input("Enter new NAME: ")
SALARY = int(input("Enter new SALARY: "))
data[i][1] = NAME
data[i][2] = SALARY
break
else:
print("Employee not found.")
choice = input("Modify another? (Y/N): ")
if choice.lower() == 'n':
break
f.seek(0)
pickle.dump(data, f)
def Delete():
with open('EMPLOYEE.DAT', 'rb+') as f:
data = pickle.load(f)
while True:
EMPNO = int(input("Enter EMPNO to delete: "))
for i in range(len(data)):
if data[i][0] == EMPNO:
data.pop(i)
break
else:
print("Employee not found.")
OUTPUT
1. Add Employee details
2. Display details
3. Search
4. Modify
5. Delete
6. Exit
Enter your choice : 1
Enter EMPNO: 1
Enter NAME : Kunjal
Enter SALARY: 12000
More? (Y/N): y
Enter EMPNO: 2
Enter NAME : Aayushi
Enter SALARY: 10000
More? (Y/N): y
Enter EMPNO: 3
Enter NAME : Kanishka
Enter SALARY: 30000
More? (Y/N): n
1. Add Employee details
2. Display details
3. Search
4. Modify
5. Delete
5. Exit
Enter your choice : 2
EMPNO NAME SALARY
1 Kunjal 12000
2 Aayushi 10000
3 Kanishka 30000
1. Add Employee details
2. Display details
3. Search
4. Modify
5. Delete
5. Exit
Enter your choice : 3
Enter EMPNO: 1
Name: Kunjal SALARY: 12000
1. Add Employee details
2. Display details
3. Search
4. Modify
5. Delete
5. Exit
Enter your choice : 4
Enter EMPNO : 2
Enter new NAME: Daksha
Enter new SALARY: 2000
Modify another? (Y/N): n
1. Add Employee details
2. Display details
3. Search
4. Modify
5. Delete
5. Exit
Enter your choice : 5
Enter EMPNO to delete: 3
More? (Y/N): n
1. Add Employee details
2. Display details
3. Search
4. Modify
5. Delete
5. Exit
1. Add Employee details
2. Display details
3. Search
4. Modify
5. Delete
5. Exit
Enter your choice : 6
Exiting
PROGRAM 10
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.
SOURCE CODE
import csv
def Create():
while True:
if choice in 'Nn':
break
import csv
def Display( ) :
try:
with open('MEMBER.CSV','r') as f:
data= csv.reader(f)
for k in data:
import csv
def Search():
data = csv.reader(f)
for k in data:
if int(k[0] == Mno):
break
else:
print("not found")
import csv
def AverageScore():
total = 0
count = 0
data = csv.reader(f)
for k in data:
total += int(k[2])
count += 1
if count > 0:
else:
while True:
print("3. Search")
print("5. Exit")
choice = input("Enter your choice : ")
if choice == '1':
Create( )
Display()
Search()
AverageScore()
print("Exiting ")
break
else:
print("Invalid choice")
OUTPUT
1. Add details of new members
2. Display details
3. Search
4. Average Fee
5. Exit
Enter Mno: 1
More? (Y/N): y
Enter Mno: 2
More? (Y/N): n
1. Add details of new members
2. Display details
3. Search
4. Average Fee
5. Exit
2. Display details
3. Search
4. Average Fee
5. Exit
Enter Mno: 2
not found
2. Display details
3. Search
4. Average Fee
5. Exit
2. Display details
3. Search
4. Average Fee
5. Exit
Exiting
PROGRAM 11
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".
SOURCE CODE
import csv
def Add():
with open('STOCK.CSV', 'a', newline='') as f:
writer = csv.writer(f)
while True:
ino = input("Enter Item No.: ")
item = input("Enter Item Name: ")
price = float(input("Enter Price: "))
qty = int(input("Enter Quantity: "))
writer.writerow([ino, item, price, qty])
choice = input("More? (Y/N): ")
if choice in 'Nn':
break
import csv
def Display():
try:
with open('STOCK.CSV', 'r') as f:
data = csv.reader(f)
print("INO", "ITEM", "PRICE", "QTY", "STOCK VALUE", sep='\t')
for k in data:
if len(k) == 4:
ino, item, price, qty = k
stock_value = float(price) * int(qty)
print(ino, item, price, qty, stock_value, sep='\t')
except FileNotFoundError:
print("No such File exists ")
import csv
def Search():
ino = input("Enter INO : ")
with open('STOCK.CSV', 'r') as f:
data = csv.reader(f)
for k in data:
if k and k[0] == ino:
print("Item found:")
print("INO:", k[0], "ITEM:", k[1], "PRICE:", k[2], "QTY:", k[3])
break
else:
print("not found.")
import csv
def P():
with open('STOCK.CSV', 'r') as f:
data = csv.reader(f)
print("Items starting with 'P':")
for k in data:
if len(k) >= 2 and k[1].startswith('P'):
print(k[1])
import csv
def Lowstock():
L = []
with open('STOCK.CSV', 'r') as f:
data = csv.reader(f)
for k in data:
if len(k) == 4 and k[3].isdigit():
qty = int(k[3])
if qty < 10:
L.append(k)
with open('REORDER.CSV', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(L)
print("Items :")
for k in L:
print(k[0], k[1], k[2], k[3], sep='\t')
while True:
print("1. Add new items")
print("2. Display all items with stock value")
print("3. Search item by INO")
print("4. Display items starting with 'P'")
print("5. Copy low stock items to REORDER.CSV")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
Add()
elif choice == '2':
Display()
elif choice == '3':
Search()
elif choice == '4':
P()
elif choice == '5':
Lowstock()
elif choice == '6':
print("Exiting program.")
break
else:
print("Invalid choice")
OUTPUT
1. Add new items
2. Display all items with stock value
3. Search item by INO
4. Display items starting with 'P'
5. Copy low stock items to REORDER.CSV
6. Exit
Enter your choice: 1
Enter Item No.: 1
Enter Item Name: Kitkat
Enter Price: 20
Enter Quantity: 5
More? (Y/N): y
Enter Item No.: 2
Enter Item Name: Mars
Enter Price: 50
Enter Quantity: 2
More? (Y/N): y
Enter Item No.: 3
Enter Item Name: Toblerone
Enter Price: 100
Enter Quantity: 3
More? (Y/N): y
Enter Item No.: 4
Enter Item Name: Pyramint
Enter Price: 130
Enter Quantity: 1
More? (Y/N): n
1. Add new items
2. Display all items with stock value
3. Search item by INO
4. Display items starting with 'P'
5. Copy low stock items to REORDER.CSV
6. Exit
Enter your choice: 2
INO ITEM PRICE QTY STOCK VALUE
1 Kitkat 20.0 5 100.0
2 Mars 50.0 2 100.0
3 Toblerone 100.0 3 300.0
4 Pyramint 130.0 1 130.0
1. Add new items
2. Display all items with stock value
3. Search item by INO
4. Display items starting with 'P'
5. Copy low stock items to REORDER.CSV
6. Exit
Enter your choice: 3
Enter INO : 2
Item found:
INO: 2 ITEM: Mars PRICE: 50.0 QTY: 2
1. Add new items
2. Display all items with stock value
3. Search item by INO
4. Display items starting with 'P'
5. Copy low stock items to REORDER.CSV
6. Exit
Enter your choice: 4
Items starting with 'P':
Pyramint
1. Add new items
2. Display all items with stock value
3. Search item by INO
4. Display items starting with 'P'
5. Copy low stock items to REORDER.CSV
6. Exit
Enter your choice: 5
Items :
1 Kitkat 20.0 5
2 Mars 50.0 2
3 Toblerone 100.0 3
4 Pyramint 130.0 1
1. Add new items
2. Display all items with stock value
3. Search item by INO
4. Display items starting with 'P'
5. Copy low stock items to REORDER.CSV
6. Exit
Enter your choice: 6
Exiting program.
PROGRAM 12
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 Add():
with open('CADETS.CSV', 'a', newline='') as f:
writer = csv.writer(f)
while True:
cno = input("Enter CNO: ")
name = input("Enter NAME: ")
gender = input("Enter GENDER : ")
age = input("Enter AGE: ")
height = input("Enter HEIGHT: ")
writer.writerow([cno, name, gender, age, height])
choice = input("More? (Y/N): ")
if choice in 'Nn':
break
def Cadets():
with open('CADETS.CSV', 'r') as f:
data = csv.reader(f)
print("CNO", "NAME", "GENDER", "AGE", "HEIGHT", sep='\t')
for k in data:
if len(k) == 5:
print(k[0], k[1], k[2], k[3], k[4], sep='\t')
import csv
def Gender():
g = input("Enter gender: ")
with open('CADETS.CSV', 'r') as f:
data = csv.reader(f)
print("CNO", "NAME", "GENDER", "AGE", "HEIGHT", sep='\t')
for k in data:
if len(k) == 5 and k[2].upper() == g.upper():
print(k[0], k[1], k[2], k[3], k[4], sep='\t')
def Modify():
cno = input("Enter CNO : ")
L= []
with open('CADETS.CSV', 'r') as f:
data = csv.reader(f)
L = list(data)
for i in range(len(L)):
if L[i][0] == cno:
new_age = input("Enter new AGE: ")
new_height = input("Enter new HEIGHT: ")
L[i][3] = new_age
L[i][4] = new_height
break
else:
print("not found")
with open('CADETS.CSV', 'w', newline='') as f:
writer = csv.writer(f)
writer.writerows(L)
while True:
print("1. Add details of new cadets")
print("2. Display all cadets")
print("3. Display cadets by gender")
print("4. Modify age and height of a cadet")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
Add()
elif choice == '2':
Cadets()
elif choice == '3':
Gender()
elif choice == '4':
Modify()
elif choice == '5':
print("Exiting program.")
break
else:
print("Invalid choice")
OUTPUT
1. Add details of new cadets
2. Display all cadets
3. Display cadets by gender
4. Modify age and height of a cadet
5. Exit
Enter your choice: 1
Enter CNO: 1
Enter NAME: Kunjal
Enter GENDER : Female
Enter AGE: 16
Enter HEIGHT: 150
More? (Y/N): y
Enter CNO: 2
Enter NAME: Aayushi
Enter GENDER : Female
Enter AGE: 16
Enter HEIGHT: 158
More? (Y/N): y
Enter CNO: 3
Enter NAME: Abhinav
Enter GENDER : Male
Enter AGE: 16
Enter HEIGHT: 164
More? (Y/N): n
1. Add details of new cadets
2. Display all cadets
3. Display cadets by gender
4. Modify age and height of a cadet
5. Exit
Enter your choice: 2
CNO NAME GENDER AGE HEIGHT
1 Kunjal Female 16 150
2 Aayushi Female 16 158
3 Abhinav Male 16 164
1. Add details of new cadets
2. Display all cadets
3. Display cadets by gender
4. Modify age and height of a cadet
5. Exit
Enter your choice: 3
Enter gender: Female
CNO NAME GENDER AGE HEIGHT
1 Kunjal Female 16 150
2 Aayushi Female 16 158
1. Add details of new cadets
2. Display all cadets
3. Display cadets by gender
4. Modify age and height of a cadet
5. Exit
Enter your choice: 4
Enter CNO : 1
Enter new AGE: 17
Enter new HEIGHT: 153
1. Add details of new cadets
2. Display all cadets
3. Display cadets by gender
4. Modify age and height of a cadet
5. Exit
Enter your choice: 5
Exiting program.
PROGRAM 13
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:
writer = csv.writer(f)
while True:
ano = input("Enter Account No: ")
name = input("Enter Name: ")
balance = input("Enter Balance: ")
writer.writerow([ano, name, balance])
choice = input("More? (Y/N): ")
if choice in 'Nn':
break
def DisplayAll():
with open('ACCOUNTS.CSV', 'r') as f:
data = csv.reader(f)
print("Ano", "Name", "Balance", sep='\t')
for k in data:
if len(k) == 3:
print(k[0], k[1], k[2], sep='\t')
while True:
print("1. Register new account holders")
print("2. Display all account holders")
print("3. Exit")
choice = input("Enter your choice: ")
if choice == '1':
Register()
OUTPUT
1. Register new account holders
3. Exit
More? (Y/N): y
More? (Y/N): n
3. Exit
1 Kunjal 12000
2 Kanu 34000
3. Exit
Exiting program.
PROGRAM 14
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'.
SOURCE CODE
BookStack = []
def Push_Book(BookStack,new_books):
Stack.append(new_books
def Pop(BookStack):
if len(BookStack)==0:
print("Underflow")
else:
return BookStack.pop()
BooksStack = []
BooksStack.append(new_book)
def pop_book(BooksStack):
if len(BooksStack) == 0:
print("Underflow")
else:
removed = BooksStack.pop()
print( removed)
def peep(BooksStack):
if len(BooksStack) == 0:
print("None")
else:
while True:
print("4. Exit")
if choice == '1':
push_book(BooksStack, new_book)
pop_book(BooksStack)
peep(BooksStack)
print("Exiting...")
break
else:
print("Invalid choice.")
OUTPUT
1. Push New Book
4. Exit
4. Exit
4. Exit
4. Exit
4. Exit
Exiting...
PROGRAM 15
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
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.
Pop_elements(Stu_Stk): It removes all elements present inside the stack in LIFO order and prints them. Also, the
function displays 'Stack Empty' when there are no elements in the stack.
Display(Stu_Stk) : It display all the elements of stack Stu_Stk. Write menu driven code to call the above functions.
SOURCE CODE
Stu_Stk = []
def push_manual(Stu_Stk):
sid = input("Enter Student ID: ")
ts3 = int(input("Enter TS3 Marks: "))
if ts3 >= 80:
Stu_Stk.append(sid)
print("Student ID pushed.")
else:
print("Not eligible.")
def pop_elements(Stu_Stk):
if not Stu_Stk:
print("Stack Empty")
else:
while Stu_Stk:
print( Stu_Stk.pop())
def display(Stu_Stk):
if not Stu_Stk:
print("Stack Empty")
else:
print("Stack contents :")
for sid in reversed(Stu_Stk):
print(sid)
while True:
print("1. Push Student ID ")
print("2. Pop All IDs")
print("3. Display Stack")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
push_manual(Stu_Stk)
elif choice == '2':
pop_elements(Stu_Stk)
elif choice == '3':
display(Stu_Stk)
elif choice == '4':
print("Exiting...")
break
else:
print("Invalid choice.")
OUTPUT
1. Push Student ID
2. Pop All IDs
3. Display Stack
4. Exit
Enter your choice: 1
Enter Student ID: 1
Enter TS3 Marks: 85
Student ID pushed.
1. Push Student ID
2. Pop All IDs
3. Display Stack
4. Exit
Enter your choice: 2
1
1. Push Student ID
2. Pop All IDs
3. Display Stack
4. Exit
Enter your choice: 3
Stack Empty
PROGRAM 16
A list, NList contains 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 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 display all the elements of stack travel. Write menu driven code to call the above functions.
SOURCE CODE
travel = []
def push_element():
travel.append([city, country])
else:
def pop_element():
if len(travel)==0:
print("Stack Empty")
else:
print(travel.pop())
def display():
if len(travel)==0:
print("Stack Empty")
else:
print("Stack :")
print(item)
while True:
print("4. Exit")
if choice == '1':
push_element()
pop_element()
display()
print("Exiting program.")
break
else:
print("Invalid choice.")
OUTPUT
1. Push a city
4. Exit
Not eligible
1. Push a city
3. Display stack
4. Exit
Stack Empty
1. Push a city
3. Display stack
4. Exit
Stack Empty
1. Push a city
3. Display stack
4. Exit
Exiting program.
PROGRAM 17
A table, named STATIONERY has the following structure:
Field Type
ItemNo Int(5) Primary key
ItemName Varchar (20)
Price Float(8,2)
Qty Int
Assume the following for Python-Database connectivity:
Host: localhost, User: root, Password: Pencil Write the following Python functions to perform the specified
operation:
A. Create() – to create a database ITEMDB, open the database and then create the above defined table
STATIONERY.
B. Insert() – to store a set of stationery items from user input in the stationery table, till user wants to store
SOURCE CODE
import mysql.connector
def Create():
con = mysql.connector.connect(host="localhost", user="root", password="Pencil")
cur = con.cursor()
cur.execute("CREATE DATABASE IF NOT EXISTS ITEMDB")
cur.execute("USE ITEMDB")
S = """
CREATE TABLE STATIONERY (
ItemNo INT(5) PRIMARY KEY,
ItemName VARCHAR(20),
Price FLOAT(8,2),
Qty INT
)
"""
cur.execute(S)
print("Table STATIONERY created successfully.")
con.close()
Create()
def Insert():
con = mysql.connector.connect(host="localhost", user="root", password="Pencil", database="ITEMDB")
cursor = con.cursor()
while True:
itemno = int(input("Enter Item Number: "))
itemname = input("Enter Item Name: ")
price = float(input("Enter Price: "))
qty = int(input("Enter Quantity: "))
query = "INSERT INTO STATIONERY (ItemNo, ItemName, Price, Qty) VALUES (%s, %s, %s, %s)"
values = (itemno, itemname, price, qty)
cursor.execute(query, values)
con.commit()
print("Item inserted successfully.")
Choice = input("More? (Y/N): ")
if Choice in 'Nn':
break
con.close()
Insert()
OUTPUT
SOURCE CODE
import mysql.connector
def display():
cur = con.cursor()
records = cur.fetchall()
if records:
else:
con.close()
def fee():
cur = con.cursor()
con.commit()
con.close()
while True:
print("3. Exit")
if ch == '1':
display()
elif ch == '2':
fee()
elif ch == '3':
print("Exiting...")
break
else:
print("Invalid choice")
OUTPUT
1. Display students with Fee > 5000
3. Exit
Fees updated
Exiting...
PROGRAM 19
STREAM VARCHAR(15)
BASIC DECIMAL(8,2)
Table: TEACHER
NAME VARCHAR(25)
AGG DECIMAL(5,1)
Table: STUDENT
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
CREATE TABLE TEACHER (
STREAM VARCHAR(15),
BASIC DECIMAL(8,2),
);
TCODE INT(3),
AGG DECIMAL(5,1),
);
SELECT `TEACHER NAME`, BASIC, BASIC * 0.25 AS `INCOME TAX` FROM TEACHER;
UPDATE STUDENT SET GRADE = 'B' WHERE AGG >= 40 AND AGG < 70;
Table: SUPPLIER
Table: PRODUCT
-- 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;
OUTPUT