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

Cs Final

The document contains a comprehensive SQL practical file for a computer science project, detailing various SQL tables and queries related to school buses, graduates, hospital patients, activities, movies, sports teams, and school uniforms. It includes instructions for creating tables, inserting data, and executing SQL queries to retrieve specific information from the databases. The file serves as a guide for performing practical SQL operations and understanding database management concepts.

Uploaded by

daddy69163
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)
18 views123 pages

Cs Final

The document contains a comprehensive SQL practical file for a computer science project, detailing various SQL tables and queries related to school buses, graduates, hospital patients, activities, movies, sports teams, and school uniforms. It includes instructions for creating tables, inserting data, and executing SQL queries to retrieve specific information from the databases. The file serves as a guide for performing practical SQL operations and understanding database management concepts.

Uploaded by

daddy69163
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/ 123

CS

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

(i) to show name and advisor of all the graduates


(ii) to show natural join
(iii) to show outer join and inner join

g) What will be the output of the following query:


(i) SELECT NAME, ADVISOR FROM GRADUATE,GUIDE WHERE
SUBJECT= MAINAREA and stipend >250;
(ii) select name,advisor from graduate,guide;

Q3. Write a SQL statement to create the following table HOSPITAL.

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;

Q4. Write SQL queries based on the following two tables:


Table: ACTIVITY
Acode ActivityName Stadium ParticipantsNum PrizeMoney ScheduleDate
1001 Relay 100x4 Star Annex 16 10000 23-Jan-2004
1002 High Jump Star Annex 10 12000 12-dec-2003
1003 Shot Put Super Power 12 8000 14-Feb-2004
1005 Long Jump Star Annex 12 9000 01-Jan-2004
1008 Discuss Throw Super Power 10 15000 19-Mar-2004

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:

(i) SELECT COUNT(DISTINCT ParticipantsNum) FROM Activity;


(ii) SELECT Max(ScheduleDate), MIN(ScheduleDate) FROM Activity;
(iii) SELECT COUNT(*) FROM Coach;
(iv) SELECT Name, Activityname FROM activity A, COACH C
WHERE A.Acode = C.Acode AND A.ParticipantsNum =10;

(v) SELECT DISTINCT Acode FROM Coach;

Q5. Write the output produced by the following SQL


statements:
a) SELECT POW(2,3);
b) SELECT ROUND(342.9234,-1);
c) SELECT LENGTH("Informatics Practices");
d) SELECT YEAR(“1979/11/26”),
MONTH(“1979/11/26”), DAY(“1979/11/26”),
MONTHNAME(“1979/11/26”);
e) SELECT LEFT("INDIA",3), RIGHT("Computer
Science",4), MID("Informatics",3,4),
SUBSTR("Practices",3);

Q6. Consider the following MOVIE table and write the SQL queries

MovieID MovieName Category ReleaseDate ProductionCost BusinessCost

001 Hindi_Movie Musical 2018-04-23 124500 130000

002 Tamil_Movie Action 2016-05-17 112000 118000

003 English_Movie Horror 2017-08-06 245000 360000

004 Bengali_Movie Adventure 2017-01-04 72000 100000

005 Telugu_Movie Action - 100000 -

006 Punjabi_Movie Comedy - 30500 -

a) Display all the information from the Movie table.


b) List business done by the movies showing only MovieID, MovieName and Total_Earning. Total_
Earning to be calculated as the sum of ProductionCost and BusinessCost.
c) List the different categories of movies.
d) Find the net profit of each movie showing its MovieID, MovieName and NetProfit. Net Profit is to
be calculated as the difference between Business Cost and Production Cost.
e) List MovieID, MovieName and Cost for all movies with
ProductionCost greater than 10,000 and less than
1,00,000.
f) List details of all movies which fall in the category of comedy or action.
g) List details of all movies which have not been released yet.
4. Suppose your school management has decided to conduct cricket matches between students of
Class XI and Class XII. Students of each class are asked to join any one of the four teams – Team
Titan, Team Rockers, Team Magnet and Team Hurricane. During summer vacations, various matches
will be conducted between these teams. Help your sports teacher to do the following:
a) Create a database “Sports”.
b) Create a table “TEAM” with following considerations:
i) It should have a column TeamID for storing an integer value between 1 to 9, which refers to
unique identification of a team.
ii) Each TeamID should have its associated name (TeamName), which should be a string of length
not less than 10 characters.
c) Using table level constraint, make TeamID as the primary key.
d) Show the structure of the table TEAM using a SQL statement.
e) As per the preferences of the students four teams were formed as given below. Insert these four
rows in
TEAM table:
Row 1: (1, Team Titan)
Row 2: (2, Team Rockers)
Row 3: (3, Team Magnet)
Row 3: (4, Team Hurricane)
f) Show the contents of the table TEAM using a DML statement.
g) Now create another table MATCH_DETAILS and insert data as shown below. Choose appropriate
data types and constraints for each attribute.
MatchID MatchDate FirstTeamID SecondTeamID FirstTeamScore SecondTeamScore

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.

b) INSERT INTO COST (UCode, Size, Price) values (7,'M',100);


When the above query is used to insert data, the values for the handkerchief without entering its
details in the UNIFORM relation is entered. Make a provision so that the data can be entered in the
COST table only if it is already there in the UNIFORM table.

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.

PCode PName UPrice Manufacturer

P01 Washing Powder 120

Surf

P02 Toothpaste 54 Colgate

P03 Soap 25 Lux

P04 Toothpaste 65 Pepsodent

P05 Soap 38 Dove

P06 Shampoo 245 Dove

Write SQL queries for the following:


a) Create the table Product with appropriate data types and constraints.
b) Identify the primary key in Product.
c) List the Product Code, Product name and price in descending order of their product name. If
PName is the same, then display the data in ascending order of price.
d) Add a new column Discount to the table Product.
e) Calculate the value of the discount in the table Product as 10 percent of the UPrice for all those
products where the UPrice is more than 100, otherwise the discount will be 0.
f) Increase the price by 12 per cent for all the products manufactured by Dove.
g) Display the total number of products manufactured by each manufacturer. Write the output(s)
produced by executing the following queries on the basis of the information given above in the table
Product:
h) SELECT PName, avg(UPrice) FROM Product GROUP BY Pname;
i) SELECT DISTINCT Manufacturer FROM Product;
j) SELECT COUNT (DISTINCT PName) FROM Product;
k) SELECT PName, MAX(UPrice), MIN(UPrice) FROM Product GROUP BY PName;
8. Using the CARSHOWROOM database given in the chapter, write the SQL queries for the following:
a) Add a new column Discount in the INVENTORY table.
b) Set appropriate discount values for all cars keeping in mind the following:
(i) No discount is available on the LXI model.
(ii) VXI model gives a 10 per cent discount.
(iii) A 12 per cent discount is given on cars other than LXI model and VXI model.
c) Display the name of the costliest car with fuel type “Petrol”.
d) Calculate the average discount and total discount available on Baleno cars.
e) List the total number of cars having no discount.
Q1.

mysql> create database questions;


Query OK, 1 row affected (0.00 sec)

mysql> show databases;


+ +
| Database |
+ +
| assign |
| d1 |
| mysql |
| questions |
| school |
| test |
+ +
6 rows in set (0.01 sec)

mysql> use questions;


Database changed
mysql> create table schoolbus
-> (Rtno int(2) primary key ,
-> Area_covered varchar(20) ,
-> capacity int(4) ,
-> No_of_students int(3) ,
-> Distance int(3) ,
-> Transporter varchar(35) ,
-> Charges int(7) );
Query OK, 0 rows affected (0.02 sec)

mysql> insert into schoolbus


-> values(1,'Vasant Kunj',100,120,10,'Shivamtravels',100000);
Query OK, 1 row affected (0.00 sec)

mysql> insert into schoolbus


-> values(2,'Hauz Khas',80,80,10,'Anand Travels',85000);
Query OK, 1 row affected (0.00 sec)

mysql> insert into schoolbus


-> values(3,'Pitampura',60,55,30,'Anand Travels',60000);
Query OK, 1 row affected (0.00 sec)

mysql> insert into schoolbus


-> values(4,'Rohini',100,90,35,'Anand Travels',100000);
Query OK, 1 row affected (0.00 sec)

mysql> insert into schoolbus


-> values(5,'Yamuna Vihar',50,60,20,'Bhalla Co.',55000);
Query OK, 1 row affected (0.02 sec)
mysql> insert into schoolbus
-> values(6,'Krishna Nagar',70,80,30,'Yadav Co.',80000);
Query OK, 1 row affected (0.02 sec)

mysql> insert into schoolbus


-> values(7,'Vasundhara',100,110,20,'Yadav Co.',100000);
Query OK, 1 row affected (0.00 sec)

mysql> insert into schoolbus


-> values(8,'Paschim Vihar',40,40,20,'Speed Travels',55000);
Query OK, 1 row affected (0.01 sec)

mysql> insert into schoolbus


-> values(9,'Saket',120,120,10,'Speed Travels',100000);
Query OK, 1 row affected (0.00 sec)

mysql> insert into schoolbus


-> values(10,'Janak Puri',100,100,20,'Kisan Tours',95000);
Query OK, 1 row affected (0.01 sec)
mysql> select * from schoolbus;
+ + + + + + + +
| Rtno | Area_covered | capacity | No_of_students | 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 | Janak Puri | 100 | 100 | 20 | Kisan Tours | 95000 |
+ + + + + + + +
10 rows in set (0.00 sec)

(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)

mysql> select transporter,sum(No_of_students) from schoolbus group by


Transporter;
+ + +
| transporter | sum(No_of_students) |
+ + +
| Anand Travels | 225 |
| Bhalla Co. | 60 |
| Kisan Tours | 100 |
| Shivamtravels | 120 |
| Speed Travels | 160 |
| Yadav Co. | 190 |
+ + +
6 rows in set (0.00 sec)

(D)

mysql> Select rtno , area_covered , Charges / No_of_students as Average from


SchoolBus;
+ + + +
| rtno | area_covered | Average |
+ + + +
| 1 | Vasant Kunj | 833.33 |
| 2 | Hauz Khas | 1062.50 |
| 3 | Pitampura | 1090.91 |
| 4 | Rohini | 1111.11 |
| 5 | Yamuna Vihar | 916.67 |
| 6 | Krishna Nagar | 1000.00 |
| 7 | Vasundhara | 909.09 |
| 8 | Paschim Vihar | 1375.00 |
| 9 | Saket | 833.33 |
| 10 | Janak Puri | 950.00 |
+ + + +
10 rows in set (0.01 sec)

(E)

mysql> insert into schoolbus


-> values(11,'Moti Bagh',35,32,10,'Kisan Tours',35000);
Query OK, 1 row affected (0.01 sec)

(G)

(i)

mysql> select sum(distance) from schoolbus where transporter='Yadav Co.';


+ +
| sum(distance) |
+ +
| 50 |
+ +
1 row in set (0.00 sec)

(ii)

mysql> select min(no_of_students) from schoolbus;


+ +
| min(no_of_students) |
+ +
| 32 |
+ +
1 row in set (0.00 sec)

(iii)

mysql> select avg(charges) from schoolbus where transporter= 'Anand travels';


+ +
| avg(charges) |
+ +
| 81666.6667 |
+ +
1 row in set (0.00 sec)

(iv)

mysql> select distinct transporter from schoolbus;


+ +
| transporter |
+ +
| Shivamtravels |
| Anand Travels |
| Bhalla Co. |
| Yadav Co. |
| Speed Travels |
| Kisan Tours |
+ +
6 rows in set (0.00 sec)
Q2.

mysql> create table Graduate


-> (S_no int(2) primary key ,
-> Name varchar(15) ,
-> Stipend int(4) ,
-> Subject varchar(20) ,
-> Average int(2) ,
-> Division varchar(2) );

mysql> insert into graduate


->
values(1,'Karan',400,'Physics',68,'I');
Query OK, 1 row affected (0.01 sec)

mysql> insert into graduate


-> values(2,'Diwakar',450,'Computer Sc.',68,'I');
Query OK, 1 row affected (0.01 sec)

mysql> insert into graduate


->
values(3,'Divya',300,'Chemistry',62,'I');
Query OK, 1 row affected (0.00 sec)

mysql> insert into graduate


-> values(4,'Rekha',350,'Physics',63,'I');
Query OK, 1 row affected (0.01 sec)

mysql> insert into graduate


->
values(5,'Arjun',500,'Maths',70,'I');
Query OK, 1 row affected (0.01 sec)

mysql> insert into graduate


-> values(6,'Sabina',400,'Chemistry',55,'II');
Query OK, 1 row affected (0.00 sec)
mysql> insert into graduate
->
values(7,'John',250,'Physics',64,'I');
Query OK, 1 row affected (0.01 sec)
mysql> insert into graduate
->
values(8,'Robert',450,'Maths',68,'I');
Query OK, 1 row affected (0.02 sec)

mysql> insert into graduate


-> values(9,'Rubina',500,'Computer Sc.',62,'I');
Query OK, 1 row affected (0.02 sec)

mysql> insert into graduate


-> values(10,'Vikas',400,'Maths',57,'II');
Query OK, 1 row affected (0.02 sec)

(A)

mysql> select * from graduate ;


+ + + + + + +
| Sno | Name | Stipend | Subject | Average | Division |
+ + + + + + +
| 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 | Chemistry | 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 |
+ + + + + + +
10 rows in set (0.01 sec)

(B)

mysql> select name,stipend,subject,stipend*12 as 'Yearly Stipend' from graduate ;


+ + + + +
| name | stipend | subject | Yearly Stipend |
+ + + + +
| Karan | 400 | Physics | 4800 |
| Diwakar | 450 | Computer Sc. | 5400 |
| Divya | 300 | Chemistry | 3600 |
| Rekha | 350 | Physics | 4200 |
| Arjun | 500 | Maths | 6000 |
| Sabina | 400 | Chemistry | 4800 |
| John | 250 | Physics | 3000 |
| Robert | 450 | Maths | 5400 |
| Rubina | 500 | Computer Sc. | 6000 |
| Vikas | 400 | Maths | 4800 |
+ + + + +
10 rows in set (0.00 sec)

(C)

mysql> select count(Subject) from graduate where subject='Physics' or 'Computer


Sc.'
;
+ +
| count(Subject) |
+ +
| 3|
+ +
1 row in set (0.01 sec)

mysql> select count(Subject) from graduate where subject='Physics' or


subject='Computer Sc.' ;
+ +
| count(Subject) |
+ +
| 5|
+ +
1 row in set (0.00 sec)
(D)

mysql> insert into graduate


-> values(11,'Kajol',300,'Computer Sc.',75,'I')
-> ;
Query OK, 1 row affected (0.01 sec)

mysql> select * from graduate;


+ + + + + + +
| Sno | Name | Stipend | Subject | Average | Division |
+ + + + + + +
| 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 | Chemistry | 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 |
| 11 | Kajol | 300 | Computer Sc. | 75 | I |
+ + + + + + +
11 rows in set (0.00 sec)

(E)

(i)

mysql> select min(average) from graduate where subject='Physics';


+ +
| min(average) |
+ +
| 63 |
+ +
1 row in set (0.00 sec)
(ii)

mysql> Select SUM(STIPEND) from GRADUATE WHERE division='II';


+ +
| SUM(STIPEND) |
+ +
| 800 |
+ +
1 row in set (0.00 sec)

(iii)

mysql> Select AVG(STIPEND) from GRADUATE where AVERAGE>=65;


+ +
| AVG(STIPEND) |
+ +
| 420.0000 |
+ +
1 row in set (0.00 sec)

(iv)

mysql> Select COUNT(distinct SUBJECT) from GRADUATE;


+ +
| COUNT(distinct SUBJECT) |
+ +
| 4|
+ +
1 row in set (0.01 sec)

(F)

mysql> create table Guide


-> (Main_Area varchar(20) ,
-> Advisor varchar(20) );
Query OK, 0 rows affected (0.04 sec)
mysql> insert into guide
-> values('Physics','Vinod');
Query OK, 1 row affected (0.03
sec)

mysql> insert into guide


-> values('Computer Sc.','Alok');
Query OK, 1 row affected (0.01 sec)

mysql> insert into guide


-> values('Chemistry','Rajan');
Query OK, 1 row affected (0.02 sec)

mysql> insert into guide


-> values('Maths','Mahesh');
Query OK, 1 row affected (0.00 sec)

(i)

mysql> select name,advisor from graduate,guide where


guide.main_area=graduate.subject
;
+ + +
| name | advisor |
+ + +
| Karan | Vinod |
| Rekha | Vinod |
| John | Vinod |
| Diwakar | Alok |
| Rubina | Alok |
| Kajol | Alok |
| Divya | Rajan |
| Sabina | Rajan |
| Arjun | Mahesh |
| Robert | Mahesh |
| Vikas | Mahesh |
+ + +
11 rows in set (0.00 sec)
(ii)

mysql> select * from graduate natural join guide ;


+ + + + + + + + +
| Sno | Name | Stipend | Subject | Average | Division | Main_Area | Advisor |
+ + + + + + + + +
| 1 | Karan | 400 | Physics | 68 | I | Physics | Vinod |
| 2 | Diwakar | 450 | Computer Sc. | 68 | I | Physics
| 3 | Divya | | Vinod |
| 4 | Rekha | 300 | Chemistry | 62 | I | Physics | Vinod |
| 5 | Arjun | 350 | Physics | 63 | I | Physics | Vinod |
6 | Sabina | 500 | Maths
| |Vinod | 70 | I | Physics |
| |Vinod
7 | John | 400 | Chemistry | 55 | II | Physics |
| Vinod 250 | Physics | 64 | I | Physics |
| 8 | Robert | 450 | Maths | 68 | I| Vinod | Physics | 500 |
Computer Sc. | |
| 9 | Rubina 62 | I | Physics | Vinod |
400
| 10| Maths
| Vikas | | 57 | II | Physics | Vinod |
300
| 11| Computer
| Kajol | Sc. | 75 | I | Physics | Vinod |
| 1| |Physics
400 Karan | | 68 | I | Computer Sc. | Alok |
| 2| |Computer
450 Diwakar |Sc. | 68 | I | Computer Sc. | Alok |
| 3 | Divya | 300 | Chemistry | 62 | I | Computer Sc. | Alok |
| 4 | Rekha | 350 | Physics | 63 | I | Computer Sc. | Alok |
| 5 | Arjun | 500 | Maths | 70 | I | Computer Sc. | Alok |
| 6 | Sabina | 400 | Chemistry | 55 | II | Computer Sc. | Alok |
| 7 | John | 250 | Physics | 64 | I | Computer Sc. | Alok |
| 8 | Robert | 450 | Maths | 68 | I | Computer Sc. | Alok |
| 9 | Rubina | 500 | Computer Sc. | 62 | I | Computer Sc. | Alok |
| 10 | Vikas | 400 | Maths | 57 | II | Computer Sc. | Alok |
| 11 | Kajol | 300 | Computer Sc. | 75 | I | Computer Sc. | Alok |
| 1 | Karan | 400 | Physics | 68 | I | Chemistry | Rajan |
| 2 | Diwakar | 450 | Computer Sc. | 68 | I | Chemistry | Rajan |
| 3 | Divya | 300 | Chemistry | 62 | I | Chemistry | Rajan |
| 4 | Rekha | 350 | Physics | 63 | I | Chemistry | Rajan |
| 5 | Arjun | 500 | Maths | 70 | I | Chemistry | Rajan |
| 6 | Sabina | 400 | Chemistry | 55 | II | Chemistry | Rajan |
| 7 | John | 250 | Physics | 64 | I | Chemistry | Rajan |
| 8 | Robert | 450 | Maths | 68 | I | Chemistry | Rajan |
| 9 | Rubina | 500 | Computer Sc. | 62 | I | Chemistry | Rajan |
| 10 | Vikas | 400 | Maths | 57 | II | Chemistry | Rajan |
| 11 | Kajol | 300 | Computer Sc. | 75 | I | Chemistry | Rajan |
| 1 | Karan | 400 | Physics | 68 | I | Maths | Mahesh |
| 2 | Diwakar | 450 | Computer Sc. | 68 | I | Maths | Mahesh |
| 3 | Divya | 300 | Chemistry | 62 | I | Maths | Mahesh |
| 4 | Rekha | 350 | Physics | 63 | I | Maths | Mahesh |
| 5 | Arjun | 500 | Maths | 70 | I | Maths | Mahesh |
| 6 | Sabina | 400 | Chemistry | 55 | II | Maths | Mahesh |
| 7 | John | 250 | Physics | 64 | I | Maths | Mahesh |
| 8 | Robert | 450 | Maths | 68 | I | Maths | Mahesh |
| 9 | Rubina | 500 | Computer Sc. | 62 | I | Maths | Mahesh |
| 10 | Vikas | 400 | Maths | 57 | II | Maths | Mahesh |
| 11 | Kajol | 300 | Computer Sc. | 75 | I | Maths | Mahesh |
+ + + + + + + + +
44 rows in set (0.00 sec)

(iii)

mysql> select name,advisor,average,stipend from graduate inner join guide on


graduate
.subject=guide.main_area ;
+ + + + +
| name | advisor | average | stipend |
+ + + + +
| Karan | Vinod | 68 | 400 |
| Rekha | Vinod | 63 | 350 |
| John | Vinod | 64 | 250 |
| Diwakar | Alok | 68 | 450 |
| Rubina | Alok | 62 | 500 |
| Kajol | Alok | 75 | 300 |
| Divya | Rajan | 62 | 300 |
| Sabina | Rajan | 55 | 400 |
| Arjun | Mahesh | 70 | 500 |
| Robert | Mahesh | 68 | 450 |
| Vikas | Mahesh | 57 | 400 |
+ + + + +
11 rows in set (0.00 sec)
(G)

(i)

mysql> SELECT NAME, ADVISOR FROM GRADUATE,GUIDE WHERE


SUBJECT= MAIN_AREA and stipend
>250;
+ + +
| NAME | ADVISOR |
+ + +
| Karan | Vinod |
| Rekha | Vinod |
| Diwakar | Alok |
| Rubina | Alok |
| Kajol | Alok |
| Divya | Rajan |
| Sabina | Rajan |
| Arjun | Mahesh |
| Robert | Mahesh |
| Vikas | Mahesh |
+ + +
10 rows in set (0.00 sec)

(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.

mysql> select * from hospital;


+ + + + + + + +
| Pno | Name | Age | Department | Dateofadm | Charges | Sex |
+ + + + + + + +
| 1 | Sandeep | 65 | Surgery | 1998-02-23 | 300 | M |
| 2 | Ravina | 24 | Orthopedic | 1998-01-01 | 200 | F |
| 3 | Karan | 45 | Orthopedic | 1998-02-19 | 200 | M |
| 4 | Tarun | 12 | Surgery | 1998-01-01 | 300 | M |
| 5 | Zubin | 36 | ENT | 1998-01-12 | 250 | M |
| 6 | Ketaki | 16 | ENT | 1998-02-24 | 300 | F |
| 7 | Ankita | 29 | Cardiology | 1998-02-20 | 800 | F |
| 8 | Zareena | 45 | Gynecology | 1998-02-22 | 300 | F |
| 9 | Kush | 19 | Cardiology | 1998-01-13 | 800 | M |
| 10 | Shailya | 31 | Medicine | 1998-02-19 | 400 | M |
+ + + + + + + +
10 rows in set (0.03 sec)

(A)

mysql> select * from hospital where department='Cardiology';


+ + + + + + + +
| Pno | Name | Age | Department | Dateofadm | Charges | Sex |
+ + + + + + + +
| 7 | Ankita | 29 | Cardiology | 1998-02-20 | 800 | F |
| 9 | Kush | 19 | Cardiology | 1998-01-13 | 800 | M |
+ + + + + + + +
2 rows in set (0.00 sec)

(B)

mysql> select name,department from hospital where sex='F' and department in


('Orthopedic','Surgery');
+ + +
| name | department |
+ + +
| Ravina | Orthopedic |
+ + +
1 row in set (0.00 sec)

(C)

mysql> select name,dateofadm from hospital order by dateofadm;


+ + +
| name | dateofadm |
+ + +
| Ravina | 1998-01-01 |
| Tarun | 1998-01-01 |
| Zubin | 1998-01-12 |
| Kush | 1998-01-13 |
| Shailya | 1998-02-19 |
| Karan | 1998-02-19 |
| Ankita | 1998-02-20 |
| Zareena | 1998-02-22 |
| Sandeep | 1998-02-23 |
| Ketaki | 1998-02-24 |
+ + +
10 rows in set (0.00 sec)

(D)

mysql> select name,charges,age from hospital where sex='M';


+ + + +
| name | charges | age |
+ + + +
| Sandeep | 300 | 65 |
| Karan | 200 | 45 |
| Tarun | 300 | 12 |
| Zubin | 250 | 36 |
| Kush | 800 | 19 |
| Shailya | 400 | 31 |
+ + + +
6 rows in set (0.00 sec)
(E)

mysql> select count(age) from hospital where age > 20;


+ +
| count(age) |
+ +
| 7|
+ +
1 row in set (0.02 sec)

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)

mysql> select distinct department from hospital;


+ +
| department |
+ +
| Surgery |
| Orthopedic |
| ENT |
| Cardiology |
| Gynecology |
| Medicine |
+ +
6 rows in set (0.01 sec)

(G)

mysql> select department,count(*) from hospital group by department;


+ + +
| department | count(*) |
+ + +
| Cardiology | 2|
| ENT | 2|
| Gynecology | 1|
| Medicine | 1|
| Orthopedic | 2|
| Surgery | 2|
+ + +
6 rows in set (0.00 sec)

(H)

mysql> select count(*) from hospital where sex='M';


+ +
| count(*) |
+ +
| 6|
+ +
1 row in set (0.01 sec)

mysql> select count(*) from hospital where sex='F';


+ +
| count(*) |
+ +
| 4|
+ +
1 row in set (0.00 sec)
(I)

mysql> select* from hospital where dateofadm > 1998-05-01;


+ + + + + + + +
| Pno | Name | Age | Department | Dateofadm | Charges | Sex |
+ + + + + + + +
| 1 | Sandeep | 65 | Surgery | 1998-02-23 | 300 | M |
| 2 | Ravina | 24 | Orthopedic | 1998-01-01 | 200 | F |
| 3 | Karan | 45 | Orthopedic | 1998-02-19 | 200 | M |
| 4 | Tarun | 12 | Surgery | 1998-01-01 | 300 | M |
| 5 | Zubin | 36 | ENT | 1998-01-12 | 250 | M |
| 6 | Ketaki | 16 | ENT | 1998-02-24 | 300 | F |
| 7 | Ankita | 29 | Cardiology | 1998-02-20 | 800 | F |
| 8 | Zareena | 45 | Gynecology | 1998-02-22 | 300 | F |
| 9 | Kush | 19 | Cardiology | 1998-01-13 | 800 | M |
| 10 | Shailya | 31 | Medicine | 1998-02-19 | 400 | M |
+ + + + + + + +
10 rows in set, 1 warning (0.01 sec)

(J)

mysql> select department,count(*) from hospital group by department having


count(*)<2;
+ + +
| department | count(*) |
+ + +
| Gynecology | 1|
| Medicine | 1|
+ + +
2 rows in set (0.01 sec)

(K)

mysql> select * from hospital where name like 'Z%';


+ + + + + + + +
| Pno | Name | Age | Department | Dateofadm | Charges | Sex |
+ + + + + + + +
| 5 | Zubin | 36 | ENT | 1998-01-12 | 250 | M |
| 8 | Zareena | 45 | Gynecology | 1998-02-22 | 300 | F |
+ + + + + + + +
2 rows in set (0.00 sec)

(L)

mysql> update hospital set age=20 where name='Kush';


Query OK, 1 row affected (0.02 sec)
Rows matched: 1 Changed: 1 Warnings: 0

mysql> select * from hospital;


+ + + + + + + +
| Pno | Name | Age | Department | Dateofadm | Charges | Sex |
+ + + + + + + +
| 1 | Sandeep | 65 | Surgery | 1998-02-23 | 300 | M |
| 2 | Ravina | 24 | Orthopedic | 1998-01-01 | 200 | F |
| 3 | Karan | 45 | Orthopedic | 1998-02-19 | 200 | M |
| 4 | Tarun | 12 | Surgery | 1998-01-01 | 300 | M |
| 5 | Zubin | 36 | ENT | 1998-01-12 | 250 | M |
| 6 | Ketaki | 16 | ENT | 1998-02-24 | 300 | F |
| 7 | Ankita | 29 | Cardiology | 1998-02-20 | 800 | F |
| 8 | Zareena | 45 | Gynecology | 1998-02-22 | 300 | F |
| 9 | Kush | 20 | Cardiology | 1998-01-13 | 800 | M |
| 10 | Shailya | 31 | Medicine | 1998-02-19 | 400 | M |
+ + + + + + + +
10 rows in set (0.00 sec)

(M)

mysql> update hospital set charges=charges + charges*0.05;


Query OK, 10 rows affected (0.00 sec)
Rows matched: 10 Changed: 10 Warnings: 0

mysql> select * from hospital;


+ + + + + + + +
| Pno | Name | Age | Department | Dateofadm | Charges | Sex |
+ + + + + + + +
| 1 | Sandeep | 65 | Surgery | 1998-02-23 | 315 | M |
| 2 | Ravina | 24 | Orthopedic | 1998-01-01 | 210 | F |
| 3 | Karan | 45 | Orthopedic | 1998-02-19 | 210 | M |
| 4 | Tarun | 12 | Surgery | 1998-01-01 | 315 | M |
| 5 | Zubin | 36 | ENT | 1998-01-12 | 262 | M |
| 6 | Ketaki | 16 | ENT | 1998-02-24 | 315 | F |
| 7 | Ankita | 29 | Cardiology | 1998-02-20 | 840 | F |
| 8 | Zareena | 45 | Gynecology | 1998-02-22 | 315 | F |
| 9 | Kush | 20 | Cardiology | 1998-01-13 | 840 | M |
| 10 | Shailya | 31 | Medicine | 1998-02-19 | 420 | M |
+ + + + + + + +
10 rows in set (0.00 sec)

(N)

mysql> delete from hospital where name='Tarun';


Query OK, 1 row affected (0.02 sec)

(O)

mysql> alter table hospital add wardnumber int(6);


Query OK, 9 rows affected (0.03 sec)
Records: 9 Duplicates: 0 Warnings: 0

mysql> select * from hospital;


+ + + + + + + + +
| Pno | Name | Age | Department | Dateofadm | Charges | Sex | wardnumber |
+ + + + + + + + +
| 1 | Sandeep | 65 | Surgery | 1998-02-23 | 315 | M | NULL |
| 2 | Ravina | 24 | Orthopedic | 1998-01-01 | 210 | F | NULL |
| 3 | Karan | 45 | Orthopedic | 1998-02-19 | 210 | M | NULL |
| 5 | Zubin | 36 | ENT | 1998-01-12 | 262 | M | NULL |
| 6 | Ketaki | 16 | ENT | 1998-02-24 | 315 | F | NULL |
| 7 | Ankita | 29 | Cardiology | 1998-02-20 | 840 | F | NULL |
| 8 | Zareena | 45 | Gynecology | 1998-02-22 | 315 | F | NULL |
| 9 | Kush | 20 | Cardiology | 1998-01-13 | 840 | M | NULL |
| 10 | Shailya | 31 | Medicine | 1998-02-19 | 420 | M | NULL |
+ + + + + + + + +
9 rows in set (0.00 sec)

(Q)

mysql> update hospital


-> set charges = NULL
-> where department='Surgery';
Query OK, 1 row affected, 1 warning (0.00 sec)
Rows matched: 1 Changed: 1 Warnings: 1

mysql> select * from hospital;


+ + + + + + + + +
| Pno | Name | Age | Department | Dateofadm | charges | Sex | wardnumber |
+ + + + + + + + +
| 1 | Sandeep | 65 | Surgery | 1998-02-23 | 0|M | NULL |
| 2 | Ravina | 24 | Orthopedic | 1998-01-01 | 210 | F | NULL |
| 3 | Karan | 45 | Orthopedic | 1998-02-19 | 210 | M | NULL |
| 5 | Zubin | 36 | ENT | 1998-01-12 | 262 | M | NULL |
| 6 | Ketaki | 16 | ENT | 1998-02-24 | 315 | F | NULL |
| 7 | Ankita | 29 | Cardiology | 1998-02-20 | 840 | F | NULL |
| 8 | Zareena | 45 | Gynecology | 1998-02-22 | 315 | F | NULL |
| 9 | Kush | 20 | Cardiology | 1998-01-13 | 840 | M | NULL |
| 10 | Shailya | 31 | Medicine | 1998-02-19 | 420 | M | NULL |
+ + + + + + + + +
9 rows in set (0.00 sec)

(R)

mysql> update hospital


-> set charges=charges-charges*0.1
-> where department='Cardiology';
Query OK, 2 rows affected (0.01 sec)
Rows matched: 2 Changed: 2 Warnings: 0
(S)

mysql> alter table hospital


-> drop primary key;
Query OK, 9 rows affected (0.02 sec)
Records: 9 Duplicates: 0 Warnings: 0

(T)

mysql> insert into hospital values(11,'Mustafa',37,'ENT','1998-02-


25',250,'M',NULL);
Query OK, 1 row affected (0.00 sec)

mysql> select * from hospital;


+ + + + + + + + +
| Pno | Name | Age | Department | Dateofadm | charges | Sex | wardnumber |
+ + + + + + + + +
| 1 | Sandeep | 65 | Surgery | 1998-02-23 | 0|M | NULL |
| 2 | Ravina | 24 | Orthopedic | 1998-01-01 | 210 | F | NULL |
| 3 | Karan | 45 | Orthopedic | 1998-02-19 | 210 | M | NULL |
| 5 | Zubin | 36 | ENT | 1998-01-12 | 262 | M | NULL |
| 6 | Ketaki | 16 | ENT | 1998-02-24 | 315 | F | NULL |
| 7 | Ankita | 29 | Cardiology | 1998-02-20 | 756 | F | NULL |
| 8 | Zareena | 45 | Gynecology | 1998-02-22 | 315 | F | NULL |
| 9 | Kush | 20 | Cardiology | 1998-01-13 | 756 | M | NULL |
| 10 | Shailya | 31 | Medicine | 1998-02-19 | 420 | M | NULL |
| 11 | Mustafa | 37 | ENT | 1998-02-25 | 250 | M | NULL |
+ + + + + + + + +
10 rows in set (0.01 sec)

(i)

mysql> Select COUNT(DISTINCT Charges) FROM Hospital;


+ +
| COUNT(DISTINCT Charges) |
+ +
| 7|
+ +
1 row in set (0.00 sec)

(ii)

mysql> Select MIN(Age) From Hospital WHERE Sex=’M’;


+ +
| MIN(Age) |
+ +
| 20 |
+ +
1 row in set (0.00 sec)

(iii)

mysql> Select AVG(Charges) FROM Hospital where DateofAdm < ’1998-02-12’;


+ +
| AVG(Charges) |
+ +
| 409.3333 |
+ +
1 row in set (0.00 sec)

(iv)

mysql> Select SUM(Charges) FROM Hospital where Sex =’F’;


+ +
| SUM(Charges) |
+ +
| 1596 |
+ +
1 row in set (0.00 sec)
Q4

mysql> create table Acticity


-> ( Acode int(4) primary key,
-> Activity_name varchar (15),
-> Stadium varchar(20),
-> Participants_num int(3),
-> Prize_money int(8),
-> Schedule_date date);
Query OK, 0 rows affected, 3 warnings (0.03 sec)

mysql> insert into acticity


-> values(1001,'Relay 100x4','Star Annex',16,10000,'2004-01-23');
Query OK, 1 row affected (0.03 sec)

mysql> insert into acticity


-> values(1002,'High Jump','Star Annex',10,12000,'2003-12-12');
Query OK, 1 row affected (0.03 sec)

mysql> insert into acticity


-> values(1003,'Shot Put','Super Power',12,8000,'2004-02-14');
Query OK, 1 row affected (0.02 sec)

mysql> insert into acticity


-> values(1005,'Long Jump','Star Annex',12,9000,'2004-01-01');
Query OK, 1 row affected (0.02 sec)

mysql> insert into acticity


-> values(1008,'Discuss Throw','Super Power',10,15000,'2004-03-19');
Query OK, 1 row affected (0.02 sec)

mysql> select * from acticity;


+ + + + + + +
| Acode | Activity_name | Stadium | Participants_num | Prize_money |
Schedule_date |
+ + + + + + +
| 1001 | Relay 100x4 | Star Annex | 16 | 10000 | 2004-01-23 |
| 1002 | High Jump | Star Annex | 10 | 12000 | 2003-12-12 |
| 1003 | Shot Put | Super Power | 12 | 8000 | 2004-02-14 |
| 1005 | Long Jump | Star Annex | 12 | 9000 | 2004-01-01 |
| 1008 | Discuss Throw | Super Power | 10 | 15000 | 2004-03-19 |
+ + + + + + +
5 rows in set (0.02 sec)

(A)

mysql> select Acode,Activity_name from acticity order by Acode desc;


+ + +
| Acode | Activity_name |
+ + +
| 1008 | Discuss Throw |
| 1005 | Long Jump |
| 1003 | Shot Put |
| 1002 | High Jump |
| 1001 | Relay 100x4 |
+ + +
5 rows in set (0.00 sec)

(B)

mysql> SELECT Stadium,SUM(Prize_Money) FROM A


CTICITY GROUP BY Stadium;
+ + +
| Stadium | SUM(Prize_Money) |
+ + +
| Star Annex | 31000 |
| Super Power | 23000 |
+ + +
2 rows in set (0.00 sec)

(C)

mysql> SELECT Name, Acode FROM COACH ORDER BY Acode;


+ + +
| Name | Acode |
+ + +
| Ahmed Hussain | 1001 |
| Janila | 1001 |
| Naaz | 1003 |
| Ravinder | 1008 |
+ + +
4 rows in set (0.00 sec)

(D)

SELECT * FROM ACTICITY WHERE Schedule_Date < '2004-01-01′ ORDER BY


Pa
rticipants_Num;
+ + + + + + +
| Acode | Activity_name | Stadium | Participants_num | Prize_money |
Schedule_date |
+ + + + + + +
| 1002 | High Jump | Star Annex | 10 | 12000 | 2003-12-12 |
+ + + + + + +
1 row in set, 1 warning (0.00 sec)

(F)

mysql> select Activity_name,Name from Acticity,coach


-> where acticity.acode=coach.acode;
+ + +
| Activity_name | Name |
+ + +
| Relay 100x4 | Ahmed Hussain |
| Relay 100x4 | Janila |
| Shot Put | Naaz |
| Discuss Throw | Ravinder |
+ + +
4 rows in set (0.00 sec)
(i)

mysql> SELECT COUNT(DISTINCT Participants_Num) FROM Acticity;


+ +
| COUNT(DISTINCT Participants_Num) |
+ +
| 3|
+ +
1 row in set (0.00 sec)

(ii)

mysql> SELECT Max(Schedule_Date), MIN(Schedule_Date) FROM Acticity;


+ + +
| Max(Schedule_Date) | MIN(Schedule_Date) |
+ + +
| 2004-03-19 | 2003-12-12 |
+ + +
1 row in set (0.00 sec)

(iii)

mysql> SELECT COUNT(*) FROM Coach;


+ +
| COUNT(*) |
+ +
| 4|
+ +
1 row in set (0.00 sec)

(iv)

mysql> SELECT Name, Activity_name FROM acticity A, COACH C WHERE


A.Acode = C
.Acode AND A.Participants_Num =10;
+ + +
| Name | Activity_name |
+ + +
| Ravinder | Discuss Throw |
+ + +
1 row in set (0.00 sec)

(v)

mysql> SELECT DISTINCT Acode FROM Coach;


+ +
| Acode |
+ +
| 1001 |
| 1003 |
| 1008 |
+-------+
3 rows in set (0.00 sec)
Q6.

mysql> CREATE TABLE MOVIE (


-> MovieID VARCHAR(3),
-> MovieName VARCHAR(50),
-> Category VARCHAR(20),
-> ReleaseDate DATE,
-> ProductionCost INT,
-> BusinessCost INT
-> );
Query OK, 0 rows affected (0.03 sec)

mysql> INSERT INTO MOVIE (MovieID, MovieName, Category, ReleaseDate,


ProductionCost, BusinessCost)
-> VALUES
-> ('001', 'Hindi_Movie', 'Musical', '2018-04-23', 124500, 130000),
-> ('002', 'Tamil_Movie', 'Action', '2016-05-17', 112000, 118000),
-> ('003', 'English_Movie', 'Horror', '2017-08-06', 245000, 360000),
-> ('004', 'Bengali_Movie', 'Adventure', '2017-01-04', 72000, 100000);
Query OK, 4 rows affected (0.03 sec)
Records: 4 Duplicates: 0 Warnings: 0

mysql> INSERT INTO MOVIE (MovieID, MovieName, Category, ProductionCost)


-> VALUES
-> ('005', 'Telugu_Movie', 'Action', 100000),
-> ('006', 'Punjabi_Movie', 'Comedy', 30500);
Query OK, 2 rows affected (0.02 sec)
Records: 2 Duplicates: 0 Warnings: 0

(A)

mysql> SELECT * FROM MOVIE;


+ + + + + + +
| MovieID | MovieName | Category | ReleaseDate | ProductionCost |
BusinessCost |
+ + + + + + +
| 001 | Hindi_Movie | Musical | 2018-04-23 | 124500 | 130000 |
| 002 | Tamil_Movie | Action | 2016-05-17 | 112000 | 118000 |
| 003 | English_Movie | Horror | 2017-08-06 | 245000 | 360000 |
| 004 | Bengali_Movie | Adventure | 2017-01-04 | 72000 | 100000 |
| 005 | Telugu_Movie | Action | NULL | 100000 | NULL |
| 006 | Punjabi_Movie | Comedy | NULL | 30500 | NULL |
+ + + + + + +
6 rows in set (0.00 sec)

(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)

mysql> SELECT DISTINCT Category


-> FROM MOVIE;
+ +
| Category |
+ +
| Musical |
| Action |
| Horror |
| Adventure |
| Comedy |
+ +
5 rows in set (0.00 sec)

(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)

mysql> CREATE DATABASE Sports;


Query OK, 1 row affected (0.03 sec)

(ii)

mysql> CREATE TABLE TEAM (


-> TeamID INT (2) ,
-> TeamName VARCHAR(50)
-> );
Query OK, 0 rows affected (0.05 sec)

(iii)

mysql> DESCRIBE TEAM;


+ + + + + + +
| Field | Type | Null | Key | Default | Extra |
+ + + + + + +
| TeamID | int | YES | | NULL | |
| TeamName | varchar(50) | YES | | NULL | |
+ + + + + + +
2 rows in set (0.03 sec)

(iv)

mysql> INSERT INTO TEAM (TeamID, TeamName)


-> VALUES
-> (1, 'Team Titan'),
-> (2, 'Team Rockers'),
-> (3, 'Team Magnet'),
-> (4, 'Team Hurricane');
Query OK, 4 rows affected (0.02 sec)
Records: 4 Duplicates: 0 Warnings: 0
(v)

mysql> SELECT * FROM TEAM;


+ + +
| TeamID | TeamName |
+ + +
| 1 | Team Titan |
| 2 | Team Rockers |
| 3 | Team Magnet |
| 4 | Team Hurricane |
+ + +
4 rows in set (0.00 sec)

(vi)

mysql> CREATE TABLE MATCH_DETAILS (


-> MatchID VARCHAR(5) PRIMARY KEY,
-> MatchDate DATE NOT NULL,
-> FirstTeamID INT NOT NULL,
-> SecondTeamID INT NOT NULL,
-> FirstTeamScore INT NOT NULL CHECK (FirstTeamScore >= 0),
-> SecondTeamScore INT NOT NULL CHECK (SecondTeamScore >= 0));
Query OK, 0 rows affected (0.03 sec)

mysql> INSERT INTO MATCH_DETAILS (MatchID, MatchDate, FirstTeamID,


SecondTeamID, FirstTeamScore, SecondTeamScore)
-> VALUES
-> ('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);
Query OK, 6 rows affected (0.01 sec)
Records: 6 Duplicates: 0 Warnings: 0
(a)

mysql> select * from match_details;


+ + + + + + +
| MatchID | MatchDate | FirstTeamID | SecondTeamID | FirstTeamScore |
SecondTeamScore |
+ + + + + + +
| 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 |
+ + + + + + +
6 rows in set (0.00 sec)

(b)

mysql> SELECT MatchID


-> FROM MATCH_DETAILS
-> WHERE FirstTeamScore > 70 AND SecondTeamScore > 70;
+ +
| MatchID |
+ +
| M1 |
+ +
1 row in set (0.00 sec)

mysql> SELECT MatchID


-> FROM MATCH_DETAILS
-> WHERE FirstTeamScore < 70 AND SecondTeamScore > 70;
+ +
| MatchID |
+ +
| M5 |
+ +
1 row in set (0.00 sec)
(c)

mysql> SELECT MatchID, MatchDate


-> FROM MATCH_DETAILS
-> WHERE
-> (FirstTeamID = 1 AND FirstTeamScore > SecondTeamScore)
-> OR
-> (SecondTeamID = 1 AND SecondTeamScore > FirstTeamScore);
+ + +
| MatchID | MatchDate |
+ + +
| M1 | 2018-07-17 |
| M3 | 2018-07-19 |
+ + +
2 rows in set (0.00 sec)

(d)

mysql> SELECT MatchID


-> FROM MATCH_DETAILS
-> WHERE
-> (FirstTeamID = 2 AND FirstTeamScore < SecondTeamScore)
-> OR
-> (SecondTeamID = 2 AND SecondTeamScore < FirstTeamScore);
+ +
| MatchID |
+ +
| M1 |
| M4 |
+ +
2 rows in set (0.00 sec)

(e)

mysql> -- Rename the table from TEAM to T_DATA


mysql> ALTER TABLE TEAM RENAME TO T_DATA;
Query OK, 0 rows affected (0.02 sec)
Q7.

mysql> CREATE TABLE UNIFORM (


-> UniformCode INT PRIMARY KEY,
-> UName VARCHAR(50) NOT NULL,
-> Color VARCHAR(20)
-> );
Query OK, 0 rows affected (0.03 sec)

mysql> CREATE TABLE COST (


-> UCode INT,
-> Size VARCHAR(10),
-> Price DECIMAL(10, 2) ,
-> PRIMARY KEY (UCode, Size),
-> FOREIGN KEY (UCode) REFERENCES UNIFORM(UniformCode)
-> );
Query OK, 0 rows affected (0.03 sec)

(A)

mysql> INSERT INTO UNIFORM (UniformCode, UName, Color)


-> VALUES (7, 'Handkerchief', 'Red');
Query OK, 1 row affected (0.01 sec)

(B)

mysql> INSERT INTO COST (UCode, Size, Price)


-> VALUES (7, 'M', 100);
Query OK, 1 row affected (0.01 sec)

(C)

mysql> ALTER TABLE COST


-> ADD CONSTRAINT fk_uniformcode
-> FOREIGN KEY (UCode) REFERENCES UNIFORM(UniformCode);
Query OK, 1 row affected (0.07 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> ALTER TABLE UNIFORM
-> MODIFY UName VARCHAR(50) NOT NULL;
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0

mysql> ALTER TABLE COST


-> ADD CONSTRAINT chk_price_positive
-> CHECK (Price > 0);
Query OK, 1 row affected (0.06 sec)
Records: 1 Duplicates: 0 Warnings: 0
Q8.

(A)

mysql> CREATE TABLE Product (


-> PCode VARCHAR(5) PRIMARY KEY,
-> PName VARCHAR(50) NOT NULL,
-> UPrice DECIMAL(10, 2) NOT NULL,
-> Manufacturer VARCHAR(50)
-> );
Query OK, 0 rows affected (0.03 sec)

mysql> INSERT INTO Product (PCode, PName, UPrice, Manufacturer)


-> VALUES
-> ('P01', 'Washing Powder', 120, 'Surf'),
-> ('P02', 'Toothpaste', 54, 'Colgate'),
-> ('P03', 'Soap', 25, 'Lux'),
-> ('P04', 'Toothpaste', 65, 'Pepsodent'),
-> ('P05', 'Soap', 38, 'Dove'),
-> ('P06', 'Shampoo', 245, 'Dove');
Query OK, 6 rows affected (0.01 sec)
Records: 6 Duplicates: 0 Warnings: 0

(C)

mysql> SELECT PCode, PName, UPrice


-> FROM Product
-> ORDER BY PName DESC, UPrice ASC;
+ + + +
| PCode | PName | UPrice |
+ + + +
| P01 | Washing Powder | 120.00 |
| P02 | Toothpaste | 54.00 |
| P04 | Toothpaste | 65.00 |
| P03 | Soap | 25.00 |
| P05 | Soap | 38.00 |
| P06 | Shampoo | 245.00 |
+ + + +
6 rows in set (0.00 sec)

(D)

mysql> ALTER TABLE Product


-> ADD Discount DECIMAL(10, 2);
Query OK, 0 rows affected (0.02 sec)
Records: 0 Duplicates: 0 Warnings: 0

(E)

mysql> UPDATE Product


-> SET Discount = CASE
-> WHEN UPrice > 100 THEN UPrice * 0.10
-> ELSE 0
-> END;
Query OK, 6 rows affected (0.01 sec)
Rows matched: 6 Changed: 6 Warnings: 0

(F)

mysql> UPDATE Product


-> SET UPrice = UPrice * 1.12
-> WHERE Manufacturer = 'Dove';
Query OK, 2 rows affected (0.01 sec)
Rows matched: 2 Changed: 2 Warnings: 0

(G)

mysql> SELECT Manufacturer, COUNT(*) AS TotalProducts


-> FROM Product
-> GROUP BY Manufacturer;
+ + +
| Manufacturer | TotalProducts |
+ + +
| Surf | 1|
| Colgate | 1|
| Lux | 1|
| Pepsodent | 1|
| | Dove 2|
+ + +
5 rows in set (0.00 sec)

(H)

mysql> SELECT PName, avg(UPrice) FROM Product GROUP BY PName;


+ + +
| PName | avg(UPrice) |
+ + +
| Washing Powder | 120.000000 |
| Toothpaste | 59.500000 |
| Soap | 33.780000 |
| Shampoo | 274.400000 |
+ + +
4 rows in set (0.00 sec)

(I)

mysql> SELECT DISTINCT Manufacturer FROM Product;


+ +
| Manufacturer |
+ +
| Surf |
| Colgate |
| Lux |
| Pepsodent |
| Dove |
+ +
5 rows in set (0.00 sec)
(J)

mysql> SELECT COUNT(DISTINCT PName) FROM Product;


+ +
| COUNT(DISTINCT PName) |
+ +
| 4|
+ +
1 row in set (0.00 sec)

(K)

mysql> SELECT PName, MAX(UPrice), MIN(UPrice) FROM Product GROUP BY


PName;
+ + + +
| PName | MAX(UPrice) | MIN(UPrice) |
+ + + +
| Washing Powder | 120.00 | 120.00 |
| Toothpaste | 65.00 | 54.00 |
| Soap | 42.56 | 25.00 |
| Shampoo | 274.40 | 274.40 |
+ + + +
4 rows in set (0.00 sec)
Computer Science Practical File
Second Term
Q1. Write a Python Program to Declare a Queue list and display the following menu:
1. Insert
2. Delete
3. Display
4. Exit
Q2. Write a Python program to create and add data in Employee table
Table: Employee
Eno Name Designation Salary Deptno
45 Ramanuj Singh Director 90000 10
32 Gareema Seth Manager 78000 20
12 John Brooke Accountant 25000 20
9 Ahmed Abdul Manager 78000 30

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

Do the following questions in Python


1. WAP to accept a List of numbers and display the following menu:

● 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

2. WAP to create a nested list of numbers and display menu

● Maximum in each sublist


● Sum in each sublist
● Minimum in list
● Average of each sublist

3. WAP to accept a tuple and do the following

● 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)

n=int(input('Enter the number of elements :'))


L=[]
for i in range(n):
ch=int(input("Enter the numbers :"))
L.append(ch)
print(L)
while True :
print("1, Reverse the list ")
print("2, Maximise the list ")
print("3, Search an element ")
print("4, Sum of all elements ")
print("5, Copy all even elements
") c=int(input("Enter your
choice :")) if c==1:
rever(L)
if c==2 :
maxi(L)
if c==3 :
el=int(input("Enter the element to be searched :"))
search(el,L)
if c==4 :
summ(L)
if c==5:
even(L)
Q2.

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)

n=int(input("Enter the number of elements in a list :"))


lis = []
for i in range(n):
lis.append([])
l=int(input("Enter the number of elements for the sublist "))
for j in range(l):
nu=int(input("Enter the element :"))
lis[i].append(nu)
print("The list is :",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))

n=int(input("Enter the number of elements :"))


tup=()
for i in range (n):
ch=input("Enter the element :")
tup+=(ch,)
print(tup)

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

2. WAP to accept number of student and accept


[Rollno, Name, father_name, mother_name,
[sub1,sub2,sub3,sub4,sub5], total, average]
create a list of n students and display the following menu:
1. Add a student
2. display result
3. Display 3 topper
4. Display number of pass and fail students
5. search on name

3. WAP to accept and do the following on a dictionary of


{itemno:
[description,price,quantity]} accept n
items
1. Add
2. Search on itemno
3. display a report in given format
itemno description price quantity total
4. modify on the basis of itemno
5. search on description

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 str (self):


net_salary = self.salary + self.allowances - self.deductions
return f"{self.empno}, {self.name}, {self.department}, {self.designation},
Net Salary: {net_salary}"

# Functions for each operation


def add_employee(employees):
empno = int(input("Enter Employee Number: "))
name = input("Enter Name: ")
department = input("Enter Department: ")
designation = input("Enter Designation: ")
salary = float(input("Enter Salary: "))
allowances = float(input("Enter Allowances: "))
deductions = float(input("Enter Deductions: "))
employees.append(Employee(empno, name, department, designation,
salary, allowances, deductions))
print("Employee added!")

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}")

# Main function with menu


def main():
employees = []
while True:
print("\n1. Add Employee")
print("2. Delete Employee")
print("3. Modify Employee")
print("4. Display Employees by Department")
print("5. Count Employees by Designation")
print("6. Exit")
choice = input("Enter your choice: ")

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.")

if name == " main ":


main()

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 str (self):


return f"{self.rollno}, {self.name}, Total: {self.total}, Average: {self.average:.2f}"
def add_student(students):
rollno = int(input("Enter Roll No: "))
name = input("Enter Name: ")
father_name = input("Enter Father's Name: ")
mother_name = input("Enter Mother's Name: ")
marks = list(map(int, input("Enter marks for 5 subjects: ").split()))
students.append(Student(rollno, name, father_name, mother_name, marks))
print("Student added!")

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.")

if name == " main ":


main()
Q3
Ans ddef add_item(items):
itemno = input("Enter Item Number: ")
if itemno in items:
print("Item already exists!")
return
description = input("Enter Description: ")
price = float(input("Enter Price: "))
quantity = int(input("Enter Quantity: "))
items[itemno] = [description, price, quantity]
print("Item added!")

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.")

if name == " main ":


main()
List of Program: file Handling
For Practical File

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.

2. Write a Menu driven program in Python to do the following


a. copy all the lines that contain the character `a&#39; in another
file and display the
another file.
b. Assume that a text file named Address.TXT already contains some
text written into it. function to read the contents of the file and replace
all words
“Delhi” with “New Delhi”
and write the changed data into a new file called NAdd.TXT
file. For example, if the Address.txt file contains the following
data: T01, Rakesh Sharma, 245-Malviya Nagar, Delhi
Replace “Delhi” with “New Delhi”

3. Write an interactive menu driven program with the following four


functions:
(a) To create a text file called “Note.txt” with some states and capitals.
(b) To display the file contents.
(c) Create another text file called “UNote.txt” to store all the states
and capitals in
uppercase
string from “Note.txt” file.
(d) Display the contents of “Note.txt” and “UNote.txt” files.

4. Write an interactive menu driven program to create a text file


called “History.TXT”
with some points about Mahatma Gandhi. Create another text file by
converting
each line of the newly created text file into a lowercase string and
display the newly
created file.
5. Write a function countDo( ) to count the presence of a word “do or Do”
in a text file
“Memo.TXT” and another function count_v() to count no of vowels in
the file. Write
a Menu driven program to call the 2 functions.

6. Write a program with a user-defined function to read the content


from a text file
MAGIC.TXT and display the following menu
a. which counts and displays the number of alphabets, digits, and
spaces present in it
b. print number of lines
c. count and display lines beginning with ‘The’ and make sure it is
not ‘There’,
‘Their’ etc
d. Count all the words beginning with a Vowel

7. A Global bank manages its customers in a binary data file “Bank.DAT”


with following
fields:
• Account Number
• Account holder’s name
• Account Balance
Give function definitions to do the following:
(a) Write a function to accept the data fields from the user and write
to file
“Bank.DAT”.
(b) Write a function to read the data records from “Bank.DAT” file and
display all the
records on the screen where the balance is more than `100000.
8. A binary file Sport.dat contains Participant name, sports, WAP to
a. create file
b. copy names of player whose sports is “Athletics” in “Atheletic.dat”.
c. display “Atheletic.dat”
9. WAP to Display menu to create, append, search in
“Telephone.dat”, binary file
having name, address and phone no of subscribers.
10. Manish is a student of class XII-B with Computer Science stream. He
has some
attributes of a student like: rollno, name, d_o_b, address, phone and
TMarks (Total
Marks). Using a suitable function write these into a binary file called
&quot;MyClass.dat&quot;
file.
a. create “MyClass.dat”
b. display result of all the students
c. accept rollno and display result
d. display top 5 students
e. count and display the students getting above 75%
11. Write a program to read the above &quot;MyClass.dat&quot;
file contents and display the
following menu.
a. Display number of pass and fail
b. Display students getting more than 60%
c. add student
d. delete student
e. modify marks after accepting rollno
12. Create a binary file with “Staff.dat” accept data in the form of tuple
(StaffId, Name, Job, Department,Basic_Sal,Allowances
Deduction,Gross_sal,Net_sal)
Gross_sal=Basic_Sal+Allowances
Net_sal=Gross_Sal-eductions
Display the following menu:
a. Create the file
b. Add in the file
c. Display all
d. Search on Name
e. Salary slip
13. Use “Staff.dat” and display the following menu
a. Accept Staffid and display
b. Accept job and count the number of employees
c. Accept Department and count number of employee
d. find total gross salary and net salary
14. Write a program that will create a binary data file “Country.DAT”
containing the
name of a country and its capital. Write an interactive menu driven
program to do
the following:
(a) Determine the country given its capital.
(b) Determine the capital given its country.
(c) Quit the program.
15. Write a program the writes data to file “books.csv” till the user
desires. Format of
the file there is no blank line after each record in the file and the
values are
separated by the character ‘@’ as shown below Store the data in
following format in
file Books.csv :
&#39;101&#39; @ &#39;python&#39; @ &#39;David&#39; @ 400.0
&#39;102&#39; @ &#39;mysql&#39; @ &#39;Pramiti&#39; @ 390.0
16. Write a python program that create and reads data from a csv
file “employee.csv”
and prints the data of employees whose salary is &lt; 10000 and
designation is
accountant.
(date of employees contain – empNo, Employee Name, Designation and
Salary)
Format of the file there is no blank line after each record in file and the
values are
separated by commas
17. Write a python program that reads data from a csv file
“employee.csv” and prints
the
data of employees whose salary is &lt; 10000 and designation is
accountant.
(date of employees contain – empNo, Employee Name, Designation and
Salary)
Format of the file each record in file has blank line after it and the values
are
separated by commas.
Q1
Ans sdef read_file_and_display_words(filename):
try:
with open(filename, 'r') as file:
for line in file:
print('#'.join(line.split()))
except FileNotFoundError:
print("File not found!")

def count_characters_in_file(filename):
try:
vowels = consonants = uppercase = lowercase = 0

with open(filename, 'r') as file:


for line in file:
for char in line:
if char.lower() in "aeiou":
vowels += 1
elif char.isalpha():
consonants += 1
elif char.isupper():
uppercase += 1
elif char.islower():
lowercase += 1

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

with open(filename, 'r') as file:


for line in file:
total_lines += 1
if line.strip().lower().startswith('the'):
lines_with_the += 1

print(f"Lines starting with 'The': {lines_with_the}")


print(f"Total lines: {total_lines}")
except FileNotFoundError:
print("File not found!")

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")

choice = input("Enter your choice: ")

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!")

if name == " main ":


main()

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 replace_and_write_address(input_filename, output_filename):


try:
with open(input_filename, 'r') as infile:
content = infile.read()

updated_content = content.replace("Delhi", "New Delhi")

with open(output_filename, 'w') as outfile:


outfile.write(updated_content)

print(f"Updated content has been written to {output_filename}.")


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")

choice = input("Enter your choice: ")

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!")

if name == " main ":


main()
Q3
Ans ddef create_note_file():
with open("Note.txt", 'w') as file:
file.write("California, Sacramento\n")
file.write("Texas, Austin\n")
file.write("New York, Albany\n")
file.write("Florida, Tallahassee\n")
file.write("Illinois, Springfield\n")
print("Note.txt created.")

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!")

if name == " main ":


main()

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.")

# Display contents of Lowercase_History.TXT


with open("Lowercase_History.TXT", 'r') as file:
print(file.read())

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")

choice = input("Enter your choice: ")

if choice == '1':
create_history_file()
elif choice == '2':
create_lowercase_file()
elif choice == '3':
break
else:
print("Invalid choice, try again!")

if name == " main ":


main()
Q5
Ans sdef countDo():
try:
with open("Memo.TXT", 'r') as file:
content = file.read()
count = content.lower().split().count('do')
print(f"The word 'do' or 'Do' appears {count} times.")
except FileNotFoundError:
print("Memo.TXT not found!")

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")

choice = input("Enter your choice: ")

if choice == '1':
countDo()
elif choice == '2':
count_v()
elif choice == '3':
break
else:
print("Invalid choice, try again!")

if name == " main ":


main()
Q6
Ans sdef
count_characters_and_spaces(): try:
with open("MAGIC.TXT", 'r') as file:
alphabets, digits, spaces = 0, 0, 0
for line in file:
for char in line:
if char.isalpha():
alphabets += 1
elif char.isdigit():
digits += 1
elif char == " ":
spaces += 1
print(f"Alphabets: {alphabets}, Digits: {digits}, Spaces: {spaces}")
except FileNotFoundError:
print("MAGIC.TXT not found!")

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")

choice = input("Enter your choice: ")

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!")

if name == " main ":


main()
Q7
Ans simport pickle

# Function to write data to the file


def write_to_file():
try:
with open("Bank.DAT", 'ab') as file:
# Accept data from user
account_number = input("Enter Account Number: ")
holder_name = input("Enter Account Holder's Name: ")
balance = float(input("Enter Account Balance: "))

# Write the data as a tuple to the file


pickle.dump((account_number, holder_name, balance), file)
print("Account information written to Bank.DAT successfully.")
except Exception as e:
print(f"Error: {e}")

# 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)

# Check if the balance is greater than 100000


if account[2] > 100000:
print(f"Account Number: {account[0]}, "
f"Holder Name: {account[1]}, "
f"Balance: {account[2]}")
found = True
except EOFError:
break
if not found:
print("No accounts found with balance greater than 100000.")
except FileNotFoundError:
print("Bank.DAT file not found!")

def main():
while True:
print("\nMenu:")
print("1. Add Account Data")
print("2. Display Accounts with Balance > 100000")
print("3. Exit")

choice = input("Enter your choice: ")

if choice == '1':
write_to_file()
elif choice == '2':
read_from_file()
elif choice == '3':
break
else:
print("Invalid choice, try again!")

if name == " main ":


main()

Q8
Ans dimport pickle

# Create Sport.dat file


def create_file():
with open("Sport.dat", "wb") as file:
n = int(input("Enter the number of participants: "))
for _ in range(n):
name = input("Enter Participant Name: ")
sport = input("Enter Sport: ")
pickle.dump((name, sport), file)
print("Sport.dat created successfully.")

# Copy Athletics players to Athletic.dat


def copy_athletics():
try:
with open("Sport.dat", "rb") as infile, open("Athletic.dat", "wb") as outfile:
while True:
try:
name, sport = pickle.load(infile)
if sport.lower() == "athletics":
pickle.dump(name, outfile)
except EOFError:
break
print("Athletics players copied to Athletic.dat.")
except FileNotFoundError:
print("Sport.dat not found!")

# 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")

choice = input("Enter your choice: ")


if choice == '1':
create_file()
elif choice == '2':
copy_athletics()
elif choice == '3':
display_athletics()
elif choice == '4':
break
else:
print("Invalid choice, try again!")
Q9
Ans dimport pickle

# Function to create a new file


def create_file():
with open("Telephone.dat", "wb") as file:
n = int(input("How many subscribers to add? "))
for _ in range(n):
name = input("Enter Name: ")
address = input("Enter Address: ")
phone = input("Enter Phone Number: ")
pickle.dump((name, address, phone), file)
print("File created successfully.")

# Function to append a record to the file


def append_to_file():
with open("Telephone.dat", "ab") as file:
name = input("Enter Name: ")
address = input("Enter Address: ")
phone = input("Enter Phone Number: ")
pickle.dump((name, address, phone), file)
print("Record added successfully.")

# Function to search for a record


def search_in_file():
try:
with open("Telephone.dat", "rb") as file:
name_to_search = input("Enter Name to Search: ")
found = False
while True:
try:
name, address, phone = pickle.load(file)
if name.lower() == name_to_search.lower():
print(f"Name: {name}, Address: {address}, Phone: {phone}")
found = True
break
except EOFError:
break
if not found:
print("Subscriber not found.")
except FileNotFoundError:
print("File not found!")

# Main menu
while True:
print("\nMenu:")
print("1. Create File")
print("2. Add Record")
print("3. Search Record")
print("4. Exit")

choice = input("Enter your choice: ")


if choice == '1':
create_file()
elif choice == '2':
append_to_file()
elif choice == '3':
search_in_file()
elif choice == '4':
break
else:
print("Invalid choice, try again!")

Q10
Ans dimport pickle

# Function to create a new file


def create_file():
with open("MyClass.dat", "wb") as file:
n = int(input("Enter number of students: "))
for _ in range(n):
rollno = input("Roll No: ")
name = input("Name: ")
marks = int(input("Total Marks: "))
pickle.dump((rollno, name, marks), file)
print("File created successfully.")

# Function to display all student records


def display_all():
try:
with open("MyClass.dat", "rb") as file:
print("All Students:")
while True:
try:
student = pickle.load(file)
print(student)
except EOFError:
break
except FileNotFoundError:
print("File not found!")

# Function to search for a student by roll number


def search_by_rollno():
try:
with open("MyClass.dat", "rb") as file:
rollno = input("Enter Roll No to search: ")
found = False
while True:
try:
student = pickle.load(file)
if student[0] == rollno:
print("Student Found:", student)
found = True
break
except EOFError:
break
if not found:
print("Student not found.")
except FileNotFoundError:
print("File not found!")

# Function to display top 5 students


def display_top_5():
try:
students = []
with open("MyClass.dat", "rb") as file:
while True:
try:
students.append(pickle.load(file))
except EOFError:
break
students.sort(key=lambda x: x[2], reverse=True)
print("Top 5 Students:")
for student in students[:5]:
print(student)
except FileNotFoundError:
print("File not found!")

# Function to count students with marks > 75


def count_above_75():
try:
count = 0
with open("MyClass.dat", "rb") as file:
while True:
try:
student = pickle.load(file)
if student[2] > 75:
count += 1
except EOFError:
break
print(f"Students with marks > 75: {count}")
except FileNotFoundError:
print("File not found!")

# 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")

choice = input("Enter your choice: ")


if choice == '1':
create_file()
elif choice == '2':
display_all()
elif choice == '3':
search_by_rollno()
elif choice == '4':
display_top_5()
elif choice == '5':
count_above_75()
elif choice == '6':
break
else:
print("Invalid choice, try again!")
Q11
Ans dimport pickle

# Function to display pass and fail students


def display_pass_fail():
try:
with open("MyClass.dat", "rb") as file:
pass_count = fail_count = 0
while True:
try:
student = pickle.load(file)
if student[2] >= 40: # Pass mark is 40
pass_count += 1
else:
fail_count += 1
except EOFError:
break
print(f"Pass: {pass_count}, Fail: {fail_count}")
except FileNotFoundError:
print("File not found!")

# Function to display students with marks > 60%


def display_above_60():
try:
with open("MyClass.dat", "rb") as file:
print("Students with marks > 60%:")
while True:
try:
student = pickle.load(file)
if student[2] > 60:
print(student)
except EOFError:
break
except FileNotFoundError:
print("File not found!")

# Function to add a student


def add_student():
try:
with open("MyClass.dat", "ab") as file:
rollno = input("Enter Roll No: ")
name = input("Enter Name: ")
marks = int(input("Enter Marks: "))
pickle.dump((rollno, name, marks), file)
print("Student added.")
except FileNotFoundError:
print("File not found!")

# Function to delete a student by roll number


def delete_student():
try:
rollno = input("Enter Roll No to delete: ")
students = []
with open("MyClass.dat", "rb") as file:
while True:
try:
student = pickle.load(file)
if student[0] != rollno:
students.append(student)
except EOFError:
break
with open("MyClass.dat", "wb") as file:
for student in students:
pickle.dump(student, file)
print("Student deleted.")
except FileNotFoundError:
print("File not found!")

# Function to modify marks of a student


def modify_marks():
try:
rollno = input("Enter Roll No to modify marks: ")
students = []
with open("MyClass.dat", "rb") as file:
while True:
try:
student = pickle.load(file)
if student[0] == rollno:
marks = int(input("Enter new marks: "))
students.append((student[0], student[1], marks))
else:
students.append(student)
except EOFError:
break
with open("MyClass.dat", "wb") as file:
for student in students:
pickle.dump(student, file)
print("Marks updated.")
except FileNotFoundError:
print("File not found!")

# 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")

choice = input("Enter your choice: ")


if choice == '1':
display_pass_fail()
elif choice == '2':
display_above_60()
elif choice == '3':
add_student()
elif choice == '4':
delete_student()
elif choice == '5':
modify_marks()
elif choice == '6':
break
else:
print("Invalid choice. Try again!")

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.")

if name == " main ":


main()
Q13
Ans dimport pickle
import os

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.")

if name == " main ":


main()
Q14
Ans dimport pickle
import os

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.")

if name == " main ":


main()

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: ")

file.write(f"'{book_id}' @ '{title}' @ '{author}' @ {price}\n")

if input("Add another? (yes/no): ").lower() != "yes":


break
print("Done writing to 'books.csv'.")

if name == " main ":


write_books_to_file()
Q16
Ans dimport csv

# Data for employees (empNo, Employee Name, Designation, Salary)


employee_data = [
[1, "John Doe", "Accountant", 8000],
[2, "Jane Smith", "Manager", 15000],
[3, "Bob Johnson", "Accountant", 9500],
[4, "Alice Brown", "Developer", 12000],
[5, "Charlie Davis", "Accountant", 7000]
]

# Create and write data to employee.csv


with open('employee.csv', mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["empNo", "Employee Name", "Designation", "Salary"]) # Writing
headers
writer.writerows(employee_data) # Writing employee data

# 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

# Read and filter data from employee.csv


with open('employee.csv', mode='r') as file:
reader = csv.reader(file)

# Skip the header row


next(reader)

print("Employees with salary < 10000 and designation 'Accountant':")

for row in reader:


if row and int(row[3]) < 10000 and row[2].lower() == "accountant":
print(f"EmpNo: {row[0]}, Name: {row[1]}, Designation: {row[2]}, Salary:
{row[3]}")
Stack Data Structure

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")

choice = input("Enter your choice: ")

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

print("Largest odd number in the stack:", largest)


else:
print("No odd numbers were entered.")
Q3
Ans dstack = []

while True: print("\


nMenu:")
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")

choice = input("Enter your choice: ")

if choice == "1":
name = input("Enter student's name: ")
stack.append(name)
print(f"{name} has been added to the stack.")

elif choice == "2":


if stack:
popped_name = stack.pop()
print(f"Popped: {popped_name}")
else:
print("Underflow: Stack is empty.")

elif choice == "3":


print("Current Stack:", stack)

elif choice == "4":


print("Exiting the program.")
break

else:
print("Invalid choice, please try again.")
Q4
Ans dword = input("Enter a word: ").lower()
stack = []

for char in word:


if char in 'aeiou' and char not in stack:
stack.append(char)

print("Unique vowels:", stack)

Q5
Ans dstack = []

while True: print("\


nMenu:")
print("1. Push")
print("2. Pop")
print("3. Display")
print("4. Exit")

choice = input("Enter your choice: ")

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.")

elif choice == "2":


if stack:
book = stack.pop()
print(f"Popped book: {book['Book Name']} by {book['Author Name']}")
else:
print("Stack is empty.")

elif choice == "3":


if stack:
print("Books in stack:")
for book in stack:
print(f"Book No: {book['Book No']}, Book Name: {book['Book Name']},
Author Name: {book['Author Name']}")
else:
print("No books in stack.")

elif choice == "4":


print("Exiting the program.")
break

else:
print("Invalid choice, try again.")

You might also like