Cs Final
Cs Final
Project
File
Name - Maanak
Yatharth
Class - XII-C Roll
NO. -
Computer Science Practical File
SQL
1.
Table : SchoolBus
Rtno Area_overed Capacity Noofstudents Distance Transporter Charges
1 Vasant kunj 100 120 10 Shivamtravels 100000
2 Hauz Khas 80 80 10 Anand travels 85000
3 Pitampura 60 55 30 Anand travels 60000
4 Rohini 100 90 35 Anand travels 100000
5 Yamuna Vihar 50 60 20 Bhalla Co. 55000
6 Krishna Nagar 70 80 30 Yadav Co. 80000
7 Vasundhara 100 110 20 Yadav Co. 100000
8 Paschim Vihar 40 40 20 Speed travels 55000
9 Saket 120 120 10 Speed travels 100000
10 Jank Puri 100 100 20 Kisan Tours 95000
(b) To show all information of students where capacity is more than the no of student in
order of rtno.
(c) To show area_covered for buses covering more than 20 km., but charges less then
80000.
(d) To show transporter wise total no. of students traveling.
(e) To show rtno, area_covered and average cost per student for all routes where
average cost per student is - charges/noofstudents.
(f) Add a new record with following data:
(11, “ Moti bagh”,35,32,10,” kisan tours “, 35000)
(g) Give the output considering the original relation as given:
(i) select sum(distance) from schoolbus where transporter= “ Yadav travels”;
(ii) select min(noofstudents) from schoolbus;
(iii) select avg(charges) from schoolbus where transporter= “ Anand travels”;
(i) select distinct transporter from schoolbus;
2.
TABLE : GRADUATE
S.NO NAME STIPEND SUBJECT AVERAGE DIV.
1 KARAN 400 PHYSICS 68 I
2 DIWAKAR 450 COMPUTER Sc. 68 I
3 DIVYA 300 CHEMISTRY 62 I
4 REKHA 350 PHYSICS 63 I
5 ARJUN 500 MATHS 70 I
6 SABINA 400 CEHMISTRY 55 II
7 JOHN 250 PHYSICS 64 I
8 ROBERT 450 MATHS 68 I
9 RUBINA 500 COMPUTER Sc. 62 I
10 VIKAS 400 MATHS 57 II
(a) List the names of those students who have obtained DIV 1 sorted by
NAME.
(b) Display a report, listing NAME, STIPEND, SUBJECT and amount of stipend
received in a year assuming that the STIPEND is paid every month.
(c) To count the number of students who are either PHYSICS or
COMPUTER Sc.
graduates.
(d) To insert a new row in the GRADUATE table:
11,”KAJOL”, 300, “computer sc”, 75, 1
(e) Give the output of following sql statement based on table GRADUATE:
(i) Select MIN(AVERAGE) from GRADUATE where
SUBJECT=”PHYSICS”;
(ii) Select SUM(STIPEND) from GRADUATE WHERE div=2;
(iii) Select AVG(STIPEND) from GRADUATE where AVERAGE>=65;
(iv) Select COUNT(distinct SUBJECT) from GRADUATE;
(f) Assume that there is one more table GUIDE in the database as shown below:
Table: GUIDE
MAINAREA ADVISOR
PHYSICS VINOD
COMPUTER SC ALOK
CHEMISTRY RAJAN
MATHEMATICS MAHESH
Table: HOSPITAL
PNo Name Age Department DateofAdm Charges Sex
1 Sandeep 65 Surgery 23/02/98 300 M
2 Ravina 24 Orthopedic 01/01/98 200 F
3 Karan 45 Orthopedic 19/02/98 200 M
4 Tarun 12 Surgery 01/01/98 300 M
5 Zubin 36 ENT 12/01/98 250 M
6 Ketaki 16 ENT 24/02/98 300 F
7 Ankita 29 Cardiology 20/02/98 800 F
8 Zareena 45 Gynecology 22/02/98 300 F
9 Kush 19 Cardiology 13/01/98 800 M
10 Shailya 31 Medicine 19/02/98 400 M
Note: PNo is the primary key in the above table.
Write SQL commands for the statements (a) to (t) on the basis of the table HOSPITAL.
a) To show all the information of the patients of cardiology department.
b) To list the names of female patients who are either in the orthopedic or surgery department.
c) To list the name of all the patients with their date of admission in ascending order.
d) To display patient’s name, charges, age for male patients only.
e) To count the number of patients with age > 20.
f) To display various departments.
g) To display the number of patients in each department.
h) To display the number of male & female patients.
i) To display the details of the patients admitted in first quarter of 1998.
j) To display the names of the department where the number of patients is less than 2.
k) To display the details of all the patients whose name starts with the alphabet ‘Z’.
l) To change the age of the patient Kush to 20.
m) To increase the charges of all the patients by 5%.
n) To remove the record of the patient whose Name is Tarun.
o) To add another column WardNumber of the type Number in the above table.
p) To change the column Charges such that it can allow NULL values.
q) To set charges to NULL for all the patients in the Surgery department.
r) To decrease the charges by 10% of all the patients admitted in the Cardiology department.
s) To remove the primary key constraint in the above table.
t) To insert a new row in the HOSPITAL table with the following data:
11,’Mustafa’,37,’ENT’,’1998-02-25’,250,’M’.
Give the output of the following SQL statements based on the above table HOSPITAL:
(i) Select COUNT(DISTINCT Charges) FROM Hospital;
(ii) Select MIN(Age) From Hospital WHERE Sex=’M’;
(iii) Select AVG(Charges) FROM Hospital where DateofAdm < ’1998-02-12’;
(iv) Select SUM(Charges) FROM Hospital where Sex =’F’;
(v) Select Name FROM Hospital where Department IN (‘ENT’, ’Orthopedic’);
(vi) Select LCASE(Department) FROM Hospital where Department Like ‘%y’;
(vii) Select department, sum(charges), max(charges) from hospital group by department;
Table: COACH
Pcode Name Acode
1 Ahmed Hussain 1001
2 Ravinder 1008
3 Janila 1001
4 Naaz 1003
a) Display the names of all the activities with their Acodes in descending order.
b) Display the sum of PrizeMoney for the activities played in each of the stadiums separately.
c) Display the coach’s name and Acodes in ascending order of Acode from the table COACH.
d) Display the content of Activity table whose ScheduleDate is earlier than 01/01/2004 in ascending
order of ParticipantsNum.
e) Display the names of coaches who are not associated with any activity at all.
f) Display the names activity and its corresponding coachname.
Give the output of the following queries:
Q6. Consider the following MOVIE table and write the SQL queries
M1 2018-07-17 1 2 90 86
M2 2018-07-18 3 4 45 48
M3 2018-07-19 1 3 78 56
M4 2018-07-19 2 4 56 67
M5 2018-07-18 1 4 32 87
M6 2018-07-17 2 3 67 51
5. Using the sports database containing two relations (TEAM, MATCH_DETAILS) and write the
queries for the following:
a) Display the MatchID of all those matches where both the teams have scored more than 70.
b) Display the MatchID of all those matches where FirstTeam has scored less than 70 but
SecondTeam has scored more than 70.
c) Display the MatchID and date of matches played by Team 1 and won by it.
d) Display the MatchID of matches played by Team 2 and not won by it.
e) Change the name of the relation TEAM to T_DATA. Also change the attributes TeamID and
TeamName to T_ID and T_NAME respectively.
Q7. A shop called Wonderful Garments who sells school uniforms maintains a database
SCHOOLUNIFORM as shown below. It consisted of two relations - UNIFORM and COST. They made
UniformCode as the primary key for UNIFORM relations. Further, they used UniformCode and Size to
be composite keys for COSTrelation. By analysing the database schema and database state, specify
SQL queries to rectify the following anomalies.
a) M/S Wonderful Garments also keeps handkerchiefs of red colour, medium size of Rs. 100 each.
c) Further, they should be able to assign a new UCode to an item only if it has a valid UName. Write a
query to add appropriate constraints to the SCHOOLUNIFORM database. d) Add the constraint so
that the price of an item is always greater than zero.
Q8. . Consider the following table named “Product”, showing details of products being sold in a
grocery shop.
Surf
(A)
mysql> select * from schoolbus where capacity > No_of_students order by Rtno;
+ + + + + + + +
| Rtno | Area_covered | capacity | No_of_students | Distance | Transporter |
Charges |
+ + + + + + + +
| 3 | Pitampura | 60 | 55 | 30 | Anand Travels | 60000 |
| 4 | Rohini | 100 | 90 | 35 | Anand Travels | 100000 |
+ + + + + + + +
2 rows in set (0.01 sec)
(B)
mysql> select Area_covered from schoolbus where Distance > 20 and Charges <
80000;
+ +
| Area_covered |
+ +
| Pitampura |
+ +
1 row in set (0.00 sec)
(C)
(D)
(E)
(G)
(i)
(ii)
(iii)
(iv)
(A)
(B)
(C)
(E)
(i)
(iii)
(iv)
(F)
(i)
(iii)
(i)
(ii)
mysql> select name,advisor from graduate,guide;
+ + +
| name | advisor |
+ + +
| Karan | Vinod |
| Diwakar | Vinod |
| Divya | Vinod |
| Rekha | Vinod |
| Arjun | Vinod |
| Sabina | Vinod |
| John | Vinod |
| Robert | Vinod |
| Rubina | Vinod |
| Vikas | Vinod |
| Kajol | Vinod |
| Karan | Alok |
| Diwakar | Alok |
| Divya | Alok |
| Rekha | Alok |
| Arjun | Alok |
| Sabina | Alok |
| John | Alok |
| Robert | Alok |
| Rubina | Alok |
| Vikas | Alok |
| Kajol | Alok |
| Karan | Rajan |
| Diwakar | Rajan |
| Divya | Rajan |
| Rekha | Rajan |
| Arjun | Rajan |
| Sabina | Rajan |
| John | Rajan |
| Robert | Rajan |
| Rubina | Rajan |
| Vikas | Rajan |
| Kajol | Rajan |
| Karan | Mahesh |
| Diwakar | Mahesh |
| Divya | Mahesh |
| Rekha | Mahesh |
| Arjun | Mahesh |
| Sabina | Mahesh |
| John | Mahesh |
| Robert | Mahesh |
| Rubina | Mahesh |
| Vikas | Mahesh |
| Kajol | Mahesh |
+ + +
44 rows in set (0.00 sec)
Q3.
(A)
(B)
(C)
(D)
mysql> select name,count(age) from hospital where age > 20 group by name;
+ + +
| name | count(age) |
+ + +
| Ankita | 1|
| Karan | 1|
| Ravina | 1|
| Sandeep | 1|
| Shailya | 1|
| Zareena | 1|
| Zubin | 1|
+ + +
7 rows in set (0.02 sec)
(F)
(G)
(H)
(J)
(K)
(L)
(M)
(N)
(O)
(Q)
(R)
(T)
(i)
(ii)
(iii)
(iv)
(A)
(B)
(C)
(D)
(F)
(ii)
(iii)
(iv)
(v)
(A)
(B)
mysql> SELECT
-> MovieID,
-> MovieName,
-> (ProductionCost + BusinessCost) AS Total_Earning
-> FROM
-> MOVIE;
+ + + +
| MovieID | MovieName | Total_Earning |
+ + + +
| 001 | Hindi_Movie | 254500 |
| 002 | Tamil_Movie | 230000 |
| 003 | English_Movie | 605000 |
| 004 | Bengali_Movie | 172000 |
| 005 | Telugu_Movie | NULL |
| 006 | Punjabi_Movie | NULL |
+ + + +
6 rows in set (0.00 sec)
(C)
(D)
mysql> SELECT
-> MovieID,
-> MovieName,
-> (BusinessCost - ProductionCost) AS NetProfit
-> FROM
-> MOVIE;
+ + + +
| MovieID | MovieName | NetProfit |
+ + + +
| 001 | Hindi_Movie | 5500 |
| 002 | Tamil_Movie | 6000 |
| 003 | English_Movie | 115000 |
| 004 | Bengali_Movie | 28000 |
| 005 | Telugu_Movie | NULL |
| 006 | Punjabi_Movie | NULL |
+ + + +
6 rows in set (0.00 sec)
(E)
mysql> SELECT
-> MovieID,
-> MovieName,
-> ProductionCost AS Cost
-> FROM
-> MOVIE
-> WHERE
-> ProductionCost > 10000 AND ProductionCost < 100000;
+ + + +
| MovieID | MovieName | Cost |
+ + + +
| 004 | Bengali_Movie | 72000 |
| 006 | Punjabi_Movie | 30500 |
+ + + +
2 rows in set (0.00 sec)
(F)
mysql> SELECT *
-> FROM MOVIE
-> WHERE
-> Category IN ('Comedy', 'Action');
+ + + + + + +
| MovieID | MovieName | Category | ReleaseDate | ProductionCost
| BusinessCost |
+ + + + + + +
| 002 | Tamil_Movie | Action | 2016-05-17 | 112000 | 118000 |
| 005 | Telugu_Movie | Action | NULL | 100000 | NULL |
| 006 | Punjabi_Movie | Comedy | NULL | 30500 | NULL |
+ + + + + + +
3 rows in set (0.00 sec)
(G)
mysql> SELECT *
-> FROM MOVIE
-> WHERE
-> ReleaseDate IS NULL;
+ + + + + + +
| MovieID | MovieName | Category | ReleaseDate | ProductionCost
| BusinessCost |
+ + + + + + +
| 005 | Telugu_Movie | Action | NULL | 100000 | NULL |
| 006 | Punjabi_Movie | Comedy | NULL | 30500 | NULL |
+ + + + + + +
2 rows in set (0.00 sec)
(i)
(ii)
(iii)
(iv)
(vi)
(b)
(d)
(e)
(A)
(B)
(C)
(A)
(C)
(D)
(E)
(F)
(G)
(H)
(I)
(K)
Q3 Write a Python program to display contents of the Employee table and Write a
Python program to accept data and insert a record in the table
Q4. Write a Python program to add a new column Department_name and city and
give update command to add department name as follows:
Table: Department
Deptno Dname City
10 Research Delhi
20 HRD Mumbai
30 Accounting Kolkata
Q5. Write a Python program to accept Eno and delete the record. Also display “Not
found” if the Eno doesnot exist in the table.
Q6. Write a Python program to accept designation and display name and salary .
Q7. Write a Python Program to Display data in tabular form
Q1.
queue=[]
def insert_element():
element = input("Enter the element to insert: ")
queue.append(element)
print(element,"has been inserted into the queue.")
def delete_element():
if len(queue) == 0:
print("Queue is empty. No elements to delete.")
else:
removed_element = queue.pop(0)
print(removed_element," has been deleted from the queue.")
def display_queue():
if len(queue) == 0:
print("Queue is empty.")
else:
print("Current Queue:", queue)
while True:
print("1. Insert")
print("2. Delete")
print("3. Display")
print("4. Exit")
choice = int(input("Enter your choice (1-4): "))
if choice == 1:
insert_element()
elif choice == 2:
delete_element()
elif choice == 3:
display_queue()
elif choice == 4:
print("Exiting the program.")
break
else:
print("Invalid choice! Please enter a valid option (1-4).")
Q2.
import mysql.connector as SQ
mycon=SQ.connect(host='localhost',user='root',passwd='Ishaan',data
base='KHMS')
if mycon.is_connected():
mycur=mycon.cursor()
mycur.execute('''Create table if not exists Employee
(Eno INT(5)PRIMARY KEY,
Name varchar(20) NOT NULL,
Designation varchar(20) NOT NULL,
Salary INT(20) NOT NULL,
Deptno INT(10) NOT NULL )''')
mycur.execute("Insert into Employee Values(45,'Ramanuj
Singh','Director',90000,10)")
mycur.execute("Insert into Employee Values(32,'Gareema
Seth','Manager',78000,20)")
mycur.execute("Insert into Employee Values(12,'John
Brooke','Accountant',25000,20)")
mycur.execute("Insert into Employee Values(9,'Ahmed
Abdul','Manager',78000,30)")
mycon.commit()
Q3.
import mysql.connector as SQ
mycon=SQ.connect(host='localhost',user='root',passwd='Ishaan',data
base='KHMS')
if mycon.is_connected():
mycur=mycon.cursor()
while True :
print("1, Displaying data ")
print("2, Inserting data ")
ch=int(input("Enter your choice
:")) if ch==1 :
mycur.execute("Select * from Employee")
myrec=mycur.fetchall()
for i in myrec:
print(i)
if ch==2:
enum=int(input("Enter the Eno :"))
na=input("Enter the name :")
desig=input("Enter designation :")
sal=int(input("Enter the salary :"))
dep=int(input("Enter the dept number :"))
S=f'insert into employee values({enum},"{na}","{desig}",{sal},
{dep})'
mycur.execute(S)
mycon.commit()
Q4.
import mysql.connector as SQ
mycon=SQ.connect(host='localhost',user='root',passwd='Ishaan',data
base='KHMS')
if mycon.is_connected():
mycur=mycon.cursor()
mycur.execute('ALTER TABLE Employee ADD COLUMN
Department_name varchar(30)')
mycur.execute('ALTER TABLE Employee ADD COLUMN City
varchar(30)')
mycur.execute('Update Employee SET Department_name =
"Research", City = "Delhi" WHERE Deptno = 10')
mycur.execute('Update Employee SET Department_name =
"HRD", City = "Mumbai" WHERE Deptno = 20')
mycur.execute('Update Employee SET Department_name =
"Accounting", City = "Kolkata" WHERE Deptno = 30')
mycon.commit()
Q5.
import mysql.connector as SQ
mycon=SQ.connect(host='localhost',user='root',passwd='Ishaan',data
base='KHMS')
if mycon.is_connected():
mycur=mycon.cursor()
delete = int(input("Enter Employee Number (Eno) to delete: "))
mycur.execute(f'SELECT * FROM Employee WHERE Eno
={delete}')
record = mycur.fetchone()
if record:
mycur.execute(f'DELETE FROM Employee WHERE Eno =
{delete}')
mycon.commit()
print("Record with Employee Number ",delete," deleted
successfully.")
else:
print("Not found")
Q6.
import mysql.connector as SQ
mycon=SQ.connect(host='localhost',user='root',passwd='Ishaan',data
base='KHMS')
if mycon.is_connected():
mycur=mycon.cursor()
desig=input("Enter the designation :")
S=(f'Select name,salary from Employee where
designation="{desig}"')
mycur.execute(S)
rec=mycur.fetchall()
for i in rec:
print(i)
ASSIGNMENT - 3
● Reverse of List
● Maximum of List
● Search in List
● Sum of all the elements of the List
● Copy all the even elements in another list
● Add in tuple
● Delete from tuple
● Find duplicate in tuple
● Search in the tuple
ASSIGNMENT - 3
Q1.
def rever(k):
k.reverse()
print("Reversed list =",k)
def maxi(v):
print("Maximum value of the list =",max(v))
def search(e,m):
for i in m:
if e==i :
print("Index of the element =",m.index(e))
def summ(l):
sum1=0
for i in l :
sum1=sum1+i
print("The sum =",sum1)
def even(l):
l1=[]
for i in l:
if i%2==0:
l1.append(i)
print("The new list =",l1)
def maxi(L):
lis = []
for p in L:
lis.append(max(p))
print("Max of sublist :",lis)
def suma(L):
lis = []
for p in L:
lis.append(sum(p))
print("Sum of sublist :",lis)
def mini(L):
lis = []
for p in L:
lis.append(min(p))
print("Min of sublist :",lis)
def ave(L):
lis = []
for p in L:
lis.append(sum(p)/len(L))
print("Avg of sublist :",lis)
while True:
print("1, for max")
print("2, for sum")
print("3, for min")
print("4, for avg")
print("5, for exit")
ch=int(input("Enter your choice :"))
if ch==1:
maxi(lis)
elif ch==2:
suma(lis)
elif ch==3:
mini(lis)
elif ch==4:
ave(lis)
elif ch==5 :
break
Sum of sublist: [46, 201]
1, for max
2, for sum
3, for min
4, for avg
5, for exit
Enter your choice :3
Min of sublist: [12, 45]
1, for max
2, for sum
3, for min
4, for avg
5, for exit
Enter your choice :4
Avg of sublist: [23.0, 100.5]
1, for max
2, for sum
3, for min
4, for avg
5, for exit
Enter your choice :I
Q3.
def add(T):
cn=input("Enter the element ")
T+=(cn,)
print("New tuple is ",T)
def dup(T):
for i in T:
if T.count(i) > 1:
print("The duplicate one is ",i)
break
def sear(T):
cn=input("Enter the element to be searched ")
for i in T:
if i==cn:
print("The index value is ",T.index(i))
while True:
print("1, for add")
print("2, for duplicate")
print("3, for sarch")
print("4, for exit")
ch=int(input("Enter your choice :"))
if ch==1:
add(tup)
elif ch==2:
dup(tup)
elif ch==3:
sear(tup)
elif ch==4 :
break
Enter your choice :3
Enter the element to be searched 34
The index value is 2
1, for add
2, for duplicate
3, for sarch
4, for exit
Enter your choice :I
WAP to accept number of employee and accept[empno,
Name, Department, Designation, Salary, Allowances,
Deductions] create a list of n employees and display the
following menu:
1. Add an employee
2. Delete an employee
3. Modify an employee
4. Accept department and display all the employees in
that department
5. Accept designation and count number of employees
Q1
Ans # Define a class to hold employee data
class Employee:
def init (self, empno, name, department, designation, salary,
allowances, deductions):
self.empno = empno
self.name = name
self.department = department
self.designation = designation
self.salary = salary
self.allowances = allowances
self.deductions = deductions
def delete_employee(employees):
empno = int(input("Enter Employee Number to delete: "))
for emp in employees:
if emp.empno == empno:
employees.remove(emp)
print("Employee deleted!")
return
print("Employee not found!")
def modify_employee(employees):
empno = int(input("Enter Employee Number to modify: "))
for emp in employees:
if emp.empno == empno:
emp.name = input(f"Enter new name (current: {emp.name}): ") or
emp.name
emp.department = input(f"Enter new department (current:
{emp.department}): ") or emp.department
emp.designation = input(f"Enter new designation (current:
{emp.designation}): ") or emp.designation
emp.salary = float(input(f"Enter new salary (current: {emp.salary}): ")
or emp.salary)
emp.allowances = float(input(f"Enter new allowances (current:
{emp.allowances}): ") or emp.allowances)
emp.deductions = float(input(f"Enter new deductions (current:
{emp.deductions}): ") or emp.deductions)
print("Employee modified!")
return
print("Employee not found!")
def display_by_department(employees):
dept = input("Enter Department: ")
dept_employees = [emp for emp in employees if emp.department == dept]
if dept_employees:
for emp in dept_employees:
print(emp)
else:
print("No employees in this department.")
def count_by_designation(employees):
designation = input("Enter Designation: ")
count = sum(1 for emp in employees if emp.designation == designation)
print(f"Number of employees with designation '{designation}': {count}")
if choice == '1':
add_employee(employees)
elif choice == '2':
delete_employee(employees)
elif choice == '3':
modify_employee(employees)
elif choice == '4':
display_by_department(employees)
elif choice == '5':
count_by_designation(employees)
elif choice == '6':
print("Exiting program.")
break
else:
print("Invalid choice, try again.")
Q2
Ans class Student:
def init (self, rollno, name, father_name, mother_name, marks):
self.rollno = rollno
self.name = name
self.father_name = father_name
self.mother_name =
mother_name self.marks = marks
self.total = sum(marks)
self.average = self.total / 5
def display_result(students):
print("\nStudent Results:")
for student in students:
print(student)
def display_toppers(students):
toppers = sorted(students, key=lambda x: x.total, reverse=True)[:3]
print("\nTop 3 Students:")
for student in toppers:
print(student)
def pass_fail_count(students):
pass_count = sum(all(mark >= 35 for mark in student.marks) for student in
students)
fail_count = len(students) - pass_count
print(f"Pass: {pass_count}, Fail: {fail_count}")
def search_by_name(students):
name = input("Enter name to search: ")
for student in students:
if student.name.lower() == name.lower():
print(student)
return
print("Student not found.")
def main():
students = []
while True:
print("\nMenu:")
print("1. Add Student")
print("2. Display Results")
print("3. Display Top 3 Students")
print("4. Pass/Fail Count")
print("5. Search by Name")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
add_student(students)
elif choice == '2':
display_result(students)
elif choice == '3':
display_toppers(students)
elif choice == '4':
pass_fail_count(students)
elif choice == '5':
search_by_name(students)
elif choice == '6':
print("Exiting...")
break
else:
print("Invalid choice. Try again.")
def search_item(items):
itemno = input("Enter Item Number to search: ")
if itemno in items:
desc, price, qty = items[itemno]
print(f"Item No: {itemno}, Description: {desc}, Price: {price}, Quantity: {qty}")
else:
print("Item not found!")
def display_report(items): print("\
nItem Report:")
print(f"{'Item No':<10}{'Description':<15}{'Price':<10}{'Quantity':<10}{'Total':<10}")
for itemno, (desc, price, qty) in items.items():
total = price * qty print(f"{itemno:<10}{desc:<15}{price:<10.2f}{qty:<10}
{total:<10.2f}")
def modify_item(items):
itemno = input("Enter Item Number to modify: ")
if itemno in items:
desc = input(f"Enter new description (current: {items[itemno][0]}): ") or
items[itemno][0]
price = float(input(f"Enter new price (current: {items[itemno][1]}): ") or
items[itemno][1])
qty = int(input(f"Enter new quantity (current: {items[itemno][2]}): ") or
items[itemno][2])
items[itemno] = [desc, price, qty]
print("Item modified!")
else:
print("Item not found!")
def search_description(items):
desc = input("Enter description to search: ").lower()
found = False
for itemno, (item_desc, price, qty) in items.items():
if desc in item_desc.lower():
print(f"Item No: {itemno}, Description: {item_desc}, Price: {price}, Quantity:
{qty}")
found = True
if not found:
print("No matching items found.")
def main():
items = {}
while True:
print("\nMenu:")
print("1. Add Item")
print("2. Search by Item Number")
print("3. Display Report")
print("4. Modify Item")
print("5. Search by Description")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
add_item(items)
elif choice == '2':
search_item(items)
elif choice == '3':
display_report(items)
elif choice == '4':
modify_item(items)
elif choice == '5':
search_description(items)
elif choice == '6':
print("Exiting program.")
break
else:
print("Invalid choice! Try again.")
1. Write a Menu driven Program in Python and read the file name from
the user:-
a. Read a text file line by line and display each word separated by a #.
b. Read a text file and display the number of vowels/
consonants/uppercase/
lowercase characters in the file.
c. Read a name of text file from the user, count and display all the
lines beginning with ‘The’, also count and display total number of
lines.
def count_characters_in_file(filename):
try:
vowels = consonants = uppercase = lowercase = 0
print(f"Vowels: {vowels}")
print(f"Consonants: {consonants}")
print(f"Uppercase: {uppercase}")
print(f"Lowercase: {lowercase}")
except FileNotFoundError:
print("File not found!")
def count_lines_starting_with_the(filename):
try:
lines_with_the = total_lines = 0
def main():
while True:
print("\nMenu:")
print("1. Display words separated by #")
print("2. Count vowels, consonants, uppercase, lowercase")
print("3. Count lines starting with 'The'")
print("4. Exit")
if choice == '1':
filename = input("Enter filename: ")
read_file_and_display_words(filename)
elif choice == '2':
filename = input("Enter filename: ")
count_characters_in_file(filename)
elif choice == '3':
filename = input("Enter filename: ")
count_lines_starting_with_the(filename)
elif choice == '4':
print("Exiting...")
break
else:
print("Invalid choice, try again!")
Q2
Ans ddef copy_lines_with_a(input_filename, output_filename):
try:
with open(input_filename, 'r') as infile, open(output_filename, 'w') as outfile:
for line in infile:
if 'a' in line:
outfile.write(line)
# Display the new file content
with open(output_filename, 'r') as outfile:
print("\nContent of the new file:")
print(outfile.read())
except FileNotFoundError:
print("File not found!")
def main():
while True:
print("\nMenu:")
print("1. Copy lines with 'a' to another file")
print("2. Replace 'Delhi' with 'New Delhi'")
print("3. Exit")
if choice == '1':
input_filename = input("Enter input filename: ")
output_filename = input("Enter output filename: ")
copy_lines_with_a(input_filename, output_filename)
elif choice == '2':
replace_and_write_address('Address.TXT', 'NAdd.TXT')
elif choice == '3':
print("Exiting...")
break
else:
print("Invalid choice, try again!")
def display_file_contents(filename):
try:
with open(filename, 'r') as file:
print(file.read())
except FileNotFoundError:
print(f"{filename} not found!")
def create_unote_file():
try:
with open("Note.txt", 'r') as infile, open("UNote.txt", 'w') as outfile:
for line in infile:
outfile.write(line.upper())
print("UNote.txt created.")
except FileNotFoundError:
print("Note.txt not found!")
def main():
while True:
print("\nMenu:")
print("1. Create Note.txt with states and capitals")
print("2. Display the contents of Note.txt")
print("3. Create UNote.txt with uppercase states and capitals")
print("4. Display contents of Note.txt and UNote.txt")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
create_note_file()
elif choice == '2':
display_file_contents("Note.txt")
elif choice == '3':
create_unote_file()
elif choice == '4':
display_file_contents("Note.txt")
display_file_contents("UNote.txt")
elif choice == '5':
break
else:
print("Invalid choice, try again!")
Q4
Ans sdef create_history_file():
with open("History.TXT", 'w') as file:
file.write("Mahatma Gandhi was a leader of the Indian independence
movement.\n")
file.write("He advocated for non-violent civil disobedience.\n")
file.write("He is known for leading the Salt March in 1930.\n")
file.write("He spent several years in South Africa fighting against apartheid.\n")
file.write("Gandhi's philosophy of Ahimsa influenced many worldwide
leaders.\n")
print("History.TXT created.")
def create_lowercase_file():
try:
with open("History.TXT", 'r') as infile, open("Lowercase_History.TXT", 'w') as
outfile:
for line in infile:
outfile.write(line.lower())
print("Lowercase_History.TXT created.")
except FileNotFoundError:
print("History.TXT not found!")
def main():
while True:
print("\nMenu:")
print("1. Create History.TXT")
print("2. Create Lowercase_History.TXT")
print("3. Exit")
if choice == '1':
create_history_file()
elif choice == '2':
create_lowercase_file()
elif choice == '3':
break
else:
print("Invalid choice, try again!")
def count_v():
vowels = "aeiouAEIOU"
try:
with open("Memo.TXT", 'r') as file:
content = file.read()
count = sum(1 for char in content if char in vowels)
print(f"Total vowels: {count}")
except FileNotFoundError:
print("Memo.TXT not found!")
def main():
while True:
print("\n1. Count 'do' or 'Do' in Memo.TXT")
print("2. Count vowels in Memo.TXT")
print("3. Exit")
if choice == '1':
countDo()
elif choice == '2':
count_v()
elif choice == '3':
break
else:
print("Invalid choice, try again!")
def count_lines():
try:
with open("MAGIC.TXT", 'r') as file:
lines = file.readlines()
print(f"Number of lines: {len(lines)}")
except FileNotFoundError:
print("MAGIC.TXT not found!")
def count_lines_starting_with_the():
try:
with open("MAGIC.TXT", 'r') as file:
count = 0
for line in file:
if line.strip().lower().startswith("the ") and not
line.lower().startswith(("there", "their")):
count += 1
print(f"Lines starting with 'The': {count}")
except FileNotFoundError:
print("MAGIC.TXT not found!")
def count_words_starting_with_vowel():
vowels = "aeiouAEIOU"
try:
with open("MAGIC.TXT", 'r') as file:
count = 0
for line in file:
words = line.split()
for word in words:
if word[0] in vowels:
count += 1
print(f"Words starting with a vowel: {count}")
except FileNotFoundError:
print("MAGIC.TXT not found!")
def main():
while True:
print("\n1. Count Alphabets, Digits, and Spaces")
print("2. Count the Number of Lines")
print("3. Count Lines Starting with 'The'")
print("4. Count Words Starting with a Vowel")
print("5. Exit")
if choice == '1':
count_characters_and_spaces()
elif choice == '2':
count_lines()
elif choice == '3':
count_lines_starting_with_the()
elif choice == '4':
count_words_starting_with_vowel()
elif choice == '5':
break
else:
print("Invalid choice, try again!")
# Function to read data from the file and display records with balance > 100000
def read_from_file():
try:
with open("Bank.DAT", 'rb') as file:
found = False
while True:
try:
# Read each record from the file
account = pickle.load(file)
def main():
while True:
print("\nMenu:")
print("1. Add Account Data")
print("2. Display Accounts with Balance > 100000")
print("3. Exit")
if choice == '1':
write_to_file()
elif choice == '2':
read_from_file()
elif choice == '3':
break
else:
print("Invalid choice, try again!")
Q8
Ans dimport pickle
# Display Athletic.dat
def display_athletics():
try:
with open("Athletic.dat", "rb") as file:
print("Players in Athletics:")
while True:
try:
print(pickle.load(file))
except EOFError:
break
except FileNotFoundError:
print("Athletic.dat not found!")
# Main menu
while True:
print("\nMenu:")
print("1. Create Sport.dat")
print("2. Copy Athletics Players to Athletic.dat")
print("3. Display Athletic.dat")
print("4. Exit")
# Main menu
while True:
print("\nMenu:")
print("1. Create File")
print("2. Add Record")
print("3. Search Record")
print("4. Exit")
Q10
Ans dimport pickle
# Main menu
while True:
print("\nMenu:")
print("1. Create File")
print("2. Display All Students")
print("3. Search by Roll No")
print("4. Display Top 5 Students")
print("5. Count Students > 75 Marks")
print("6. Exit")
# Main menu
while True:
print("\nMenu:")
print("1. Display Pass and Fail")
print("2. Display Students with > 60% Marks")
print("3. Add Student")
print("4. Delete Student")
print("5. Modify Marks")
print("6. Exit")
Q12
Ans dimport pickle
import os
def create_file():
with open("Staff.dat", "wb") as file:
print("File created.")
def add_to_file():
staff_id = input("Staff ID: ")
name = input("Name: ")
job = input("Job: ")
department = input("Department: ")
basic_sal = float(input("Basic Salary: "))
allowances = float(input("Allowances: "))
deduction = float(input("Deduction: "))
gross_sal = basic_sal + allowances
net_sal = gross_sal - deduction
record = (staff_id, name, job, department, basic_sal, allowances, deduction,
gross_sal, net_sal)
with open("Staff.dat", "ab") as file:
pickle.dump(record, file)
print("Record added.")
def display_all():
if not os.path.exists("Staff.dat"):
print("File not found.")
return
with open("Staff.dat", "rb") as file:
try:
while True:
print(pickle.load(file))
except EOFError:
pass
def search_on_name():
name = input("Name to search: ")
if not os.path.exists("Staff.dat"):
print("File not found.")
return
with open("Staff.dat", "rb") as file:
found = False
try:
while True:
record = pickle.load(file)
if record[1].lower() == name.lower():
print("Found:", record)
found = True
break
except EOFError:
if not found:
print("No record found.")
def generate_salary_slip():
name = input("Name for salary slip: ")
if not os.path.exists("Staff.dat"):
print("File not found.")
return
with open("Staff.dat", "rb") as file:
found = False
try:
while True:
record = pickle.load(file)
if record[1].lower() == name.lower():
print(f"\nSalary Slip\nStaff ID: {record[0]}\nName: {record[1]}\nJob:
{record[2]}\nDepartment: {record[3]}\nBasic: {record[4]}\nAllowances:
{record[5]}\nDeduction: {record[6]}\nGross: {record[7]}\nNet: {record[8]}")
found = True
break
except EOFError:
if not found:
print("No record found.")
def main():
while True:
print("\nMenu:\na. Create File\nb. Add Record\nc. Display All\nd. Search by
Name\ne. Salary Slip\nf. Exit")
choice = input("Choice: ").lower()
if choice == 'a':
create_file()
elif choice == 'b':
add_to_file()
elif choice == 'c':
display_all()
elif choice == 'd':
search_on_name()
elif choice == 'e':
generate_salary_slip()
elif choice == 'f':
print("Exiting.")
break
else:
print("Invalid choice.")
def display_by_staffid():
staff_id = input("Enter Staff ID: ")
if os.path.exists("Staff.dat"):
with open("Staff.dat", "rb") as file:
try:
while True:
record = pickle.load(file)
if record[0] == staff_id:
print("Record:", record)
return
except EOFError:
pass
print("Staff ID not found.")
def count_by_job():
job = input("Enter Job: ")
count = 0
if os.path.exists("Staff.dat"):
with open("Staff.dat", "rb") as file:
try:
while True:
record = pickle.load(file)
if record[2].lower() == job.lower():
count += 1
except EOFError:
pass
print(f"Employees with job '{job}': {count}")
def count_by_department():
department = input("Enter Department: ")
count = 0
if os.path.exists("Staff.dat"):
with open("Staff.dat", "rb") as file:
try:
while True:
record = pickle.load(file)
if record[3].lower() == department.lower():
count += 1
except EOFError:
pass
print(f"Employees in department '{department}': {count}")
def main():
while True:
print("\nMenu:\na. Display by Staff ID\nb. Count by Job\nc. Count by
Department\nd. Exit")
choice = input("Choice: ").lower()
if choice == 'a':
display_by_staffid()
elif choice == 'b':
count_by_job()
elif choice == 'c':
count_by_department()
elif choice == 'd':
print("Exiting.")
break
else:
print("Invalid choice.")
def add_country():
country = input("Country: ")
capital = input("Capital: ")
with open("Country.DAT", "ab") as file:
pickle.dump((country, capital), file)
print("Added.")
def find_country_by_capital():
capital = input("Capital: ")
if os.path.exists("Country.DAT"):
with open("Country.DAT", "rb") as file:
try:
while True:
country, cap = pickle.load(file)
if cap.lower() == capital.lower():
print("Country:", country)
return
except EOFError:
pass
print("Not found.")
def find_capital_by_country():
country = input("Country: ")
if os.path.exists("Country.DAT"):
with open("Country.DAT", "rb") as file:
try:
while True:
cnt, capital = pickle.load(file)
if cnt.lower() ==
country.lower():
print("Capital:", capital)
return
except EOFError:
pass
print("Not found.")
def main():
while True:
print("\nMenu:\n1. Add Country and Capital\n2. Find Country by Capital\n3.
Find Capital by Country\n4. Quit")
choice = input("Choice: ")
if choice == '1':
add_country()
elif choice == '2':
find_country_by_capital()
elif choice == '3':
find_capital_by_country()
elif choice == '4':
print("Goodbye!")
break
else:
print("Invalid choice.")
Q15
Ans ddef write_books_to_file():
with open("books.csv", "a") as file:
while True:
book_id = input("Book ID: ")
title = input("Title: ")
author = input("Author: ")
price = input("Price: ")
# Read data from employee.csv and print employees whose salary is < 10000 and
designation is "Accountant"
with open('employee.csv', mode='r') as file:
reader = csv.reader(file)
next(reader) # Skip the header row
print("Employees with salary < 10000 and designation 'Accountant':")
for row in reader:
emp_no, name, designation, salary = row
if int(salary) < 10000 and designation.lower() == "accountant":
print(f"EmpNo: {emp_no}, Name: {name}, Designation: {designation}, Salary:
{salary}")
Q17
Ans dimport csv
Q1. Write a Python Program to Declare a Stack list and display the
following menu:
1. Push
2. Pop
3. Display
4. Exit
Q2. Write a program to create a Stack for storing only odd numbers out
of all
the numbers entered by the user. Display the content of the Stack along
with
the largest odd number in the Stack. (Hint. Keep popping out the
elements
from the stack and maintain the largest element retrieved so far in a
variable.
Repeat till Stack is empty)
Q3. Sunita wants to create a stack to store names of students appearing
for an interview.
Write a Python Program to Declare a Stack list and display the following
menu:
1. Push
2. Pop
3. Display
4. Exit
Option 1: Accept name from the user and push in the stack
Option 2: Remove the topmost element from the stack. Function should
return the popped
element or -1 if the stack is empty. Display popped element in the main
function and display
“Underflow” if the function returns -1
Option 3: Display the stack
Q4. Write a program to display unique vowels present in the given word
using Stack.
Q5. Write a Menu Driven Python Program to perform different
operations on STACK
containing details of Books like Book No., Book name, Author name.
The menu shows the following options: 1. Push 2. Pop 3. Display 4. Exit
Q1
Ans dstack = []
def push():
item = input("Enter the item to push onto the stack: ")
stack.append(item)
print(f"{item} has been pushed onto the stack.")
def pop():
if len(stack) > 0:
item = stack.pop()
print(f"{item} has been popped from the stack.")
else:
print("Stack is empty, cannot pop.")
def display():
if len(stack) > 0:
print("Stack contents:", stack)
else:
print("Stack is empty.")
def menu():
while True:
print("\nMenu:")
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")
if choice == "1":
push()
elif choice == "2":
pop()
elif choice == "3":
display()
elif choice == "4":
print("Exiting the program.")
break
else:
print("Invalid choice, please try again.")
menu()
Q2
Ans dstack = []
while True:
number = int(input("Enter a number (or 0 to stop): "))
if number == 0:
break
if number % 2 != 0: # Check if the number is odd
stack.append(number)
if stack:
largest = None
print("Stack contents:", stack)
while stack:
number = stack.pop()
if largest is None or number > largest:
largest = number
if choice == "1":
name = input("Enter student's name: ")
stack.append(name)
print(f"{name} has been added to the stack.")
else:
print("Invalid choice, please try again.")
Q4
Ans dword = input("Enter a word: ").lower()
stack = []
Q5
Ans dstack = []
if choice == "1":
book_no = input("Enter Book No: ")
book_name = input("Enter Book Name: ")
author_name = input("Enter Author Name: ")
stack.append({'Book No': book_no, 'Book Name': book_name, 'Author Name':
author_name})
print(f"Book '{book_name}' by {author_name} has been added.")
else:
print("Invalid choice, try again.")