Friday, 1 August 2025

GRADE 12 : PRACTICAL 17

Create the tables given below, and perform the given queries 

ORDERS

ITEM


CREATE TABLE Item (

    ItemID INT PRIMARY KEY,
    ItemName VARCHAR(50),
    Category VARCHAR(30),
    Price DECIMAL(10,2),
    StockQty INT
);

INSERT INTO Item (ItemID, ItemName, Category, Price, StockQty) VALUES
(101, 'Pen', 'Stationery', 10.00, 150),
(102, 'Notebook', 'Stationery', 50.00, 100),
(103, 'Water Bottle', 'Accessories', 120.00, 75),
(104, 'Pencil Box', 'Stationery', 80.00, 60),
(105, 'Backpack', 'Bags', 500.00, 30);

CREATE TABLE Orders (
    OrderID INT PRIMARY KEY,
    OrderDate DATE,
    CustomerName VARCHAR(50),
    ItemID INT,
    Quantity INT,
    FOREIGN KEY (ItemID) REFERENCES Item(ItemID)
);

INSERT INTO Orders (OrderID, OrderDate, CustomerName, ItemID, Quantity) VALUES
(201, '2025-07-15', 'Riya Sharma', 101, 3),
(202, '2025-07-16', 'Aarav Mehta', 105, 1),
(203, '2025-07-17', 'Neha Sinha', 102, 2),
(204, '2025-07-17', 'Aditya Rao', 103, 1),
(205, '2025-07-18', 'Isha Verma', 104, 2);


1. Show each customer's total bill amount

2. Display items where Total quantity ordered per item

3. Show the order id, orderdate , customer name and item name of the items ordered on 17-07-2025

4. List all orders with item names in descending order of quantity

5. Decrease the stock for pen by 5

6. Show categories and number of items in that category sorted by average price descending 

7. Show all items with second letter as 'a'
 
8. Find the item with the maximum price

9. Show the most recently placed order

10. Delete order entries where pencil box is bought.


Sunday, 27 July 2025

GRADE 12 : PRACTICAL 16

 Create the below tables and perform the required queries:


FURNITURE:


+----+-----------------+--------------+-------------+----------+----------+

| no | itemname        | type         | dateofstock | price    | discount |

+----+-----------------+--------------+-------------+----------+----------+

|  1 | dolphin         | baby cot     | 19-02-2002  |  9500.00 |       20 |

|  2 | decent          | office table | 01-01-2002  | 25000.00 |       30 |

|  3 | comfort zone    | double bed   | 12-01-2002  | 25000.00 |       25 |

|  4 | donald          | baby cot     | 24-02-2002  |  6500.00 |       15 |

|  5 | royal finish    | office table | 20-02-2002  | 18000.00 |       90 |

|  6 | royal tiger     | sofa         | 22-02-2002  | 31000.00 |       30 |

|  7 | economy sitting | sofa         | 13-12-2001  |  9500.00 |       25 |

|  8 | eating paradise | dining table | 19-02-2002  | 11500.00 |       25 |

+----+-----------------+--------------+-------------+----------+----------+  


ARRIVALS:


+----+--------------+------------+-------------+----------+----------+

| no | itemname     | type       | dateofstock | price    | discount |

+----+--------------+------------+-------------+----------+----------+

|  1 | wood comfort | double bed | 23-03-2003  | 25000.00 |       25 |

|  2 | old fox      | sofa       | 20-03-2003  | 17000.00 |       20 |

|  3 | micky        | baby cot   | 1-4-2003    |  7500.00 |       15 |

+----+--------------+------------+-------------+----------+----------+


CREATE STATEMENTS :


CREATE DATABASE lab16;

USE lab16;


create table furniture(

no int primary key,

itemname varchar(50) not null, 

type varchar(50) not null,

dateofstock date not null,

price decimal(8,2), 

discount numeric(2)

);


create table arrivals(

no int primary key , 

itemname varchar(50) not null, 

type varchar(50) not null,

dateofstock date not null,

price decimal(8,2) not null, 

discount numeric(2) 

);


insert into furniture values 

(1,'dolphin','baby cot','2002-02-19',9500.00,20),

(2,'decent','office table','2002-01-01',25000.00,30),

(3,'comfort zone','double bed','2002-01-12',25000.00,25),

(4,'donald','baby cot','2002-02-24',6500.00,15),

(5,'royal finish','office table','2002-02-20',18000.00,90),

(6,'royal tiger','sofa','2002-02-22',31000.00,30),

(7,'economy sitting','sofa','2001-12-13',9500.00,25),

(8,'eating paradise','dining table','2002-02-19',11500.00,25);


insert into arrivals values 

(1,'wood comfort','double bed','2003-03-23',25000.00,25),

(2,'old fox','sofa','2003-03-20',17000.00,20),

(3,'micky','baby cot','2003-4-1',7500.00,15);



QUERIES

i)List itemnames and types of those items which were stocked in February from the furniture table in descending order of the item name


ii)Display item name and date of stock of those items in which the discount percentage is less than 20 or more than 25.


iii)Display the number of furniture items for each type

iv) Find the maximum discount offered on each furniture type


v)Display furniture items having a price greater than the average price of all arrivals.


vi)Display furniture types that are not present in the arrivals table

vii) Display item no, item name, mrp and the discounted price for all items


viii)Move all the rows from arrivals into the furniture table


ix)Increase the discount by 5 for all 'sofa' type items in the furniture table.

x)Remove all furniture items that were stocked before January 1, 2002.



Thursday, 24 July 2025

GRADE 12 : PRACTICAL 15

  

Create the below tables : 

Student:

Stream:

CREATE TABLE STREAM (
    s_id INT PRIMARY KEY,
    s_name VARCHAR(20)
);
CREATE TABLE STUDENT (
    adno INT PRIMARY KEY,
    fname VARCHAR(20),
    lname VARCHAR(20),
    class VARCHAR(5),
    sec CHAR(1),
    fee INT,
    mobile BIGINT,
    area VARCHAR(30),
    s_id INT,
    FOREIGN KEY (s_id) REFERENCES STREAM(s_id)
);


INSERT INTO STREAM VALUES 
(10, 'PCMC'),
(20, 'PCMB'),
(30, 'PCBH'),
(40, 'HECA'),
(50, 'MECA'),
(60, 'Arts');

INSERT INTO STUDENT VALUES 
(1001, 'Ramesh', 'Babu', 'xii', 'a', 5000, 9988776655, 'Benson Town', 10),
(1002, 'Dipti', 'Rai', 'xii', 'b', 4500, 8877665599, 'Cooke Town', 20),
(1003, 'Rahul', 'Pai', 'xii', 'c', 4000, 7766559988, 'Fraser Town', 30),
(1004, 'Shruthi', 'Saravanan', 'xii', 'c', 4000, 6655998877, 'Benson Town', 30),
(1005, 'George', 'Davis', 'xi', 'a', 4500, 5599887766, 'Cooke town', 10),
(1006, 'Tinu', 'Anna', 'xi', 'b', 4200, 9988776611, 'Benson Town', 20),
(1007, 'Abrar', 'Sultan', 'xi', 'c', 4100, 9988776622, 'Cooke town', 40),
(1008, 'Iffath', 'Khan', 'xii', 'a', 5000, 9988776633, 'Fraser Town', 10),
(1009, 'Hansika', 'Singh', 'xii', 'b', 4500, 9988776644, 'Cleveland Town', 20),
(1010, 'Kailash', 'Dharyanani', 'xii', 'c', 4000, 9988776633, 'Richard Town', 50);


1)Display each student's full name along with their stream name.
SELECT CONCAT(fname,' ',lname) AS FullName, s_name
FROM STUDENT NATURAL JOIN STREAM;

2)List the names of streams and the number of students in each.
SELECT s_name, COUNT(*) AS Num_Students
FROM STREAM NATURAL JOIN STUDENT 
GROUP BY s_name;

3)Find the total fee collected from each class
SELECT class, SUM(fee) AS Total_Fee
FROM STUDENT
GROUP BY class;

4)List the average fee paid by students in each stream
SELECT s_name, AVG(fee) AS Avg_Fee
FROM STUDENT NATURAL JOIN STREAM 
GROUP BY s_name;

5)Display the student(s) who paid the highest fee.
SELECT fname, lname, fee
FROM STUDENT
WHERE fee = (SELECT MAX(fee) FROM STUDENT);

6)Display the stream name and the total fee collected (highest total first), where the fee collected is more than Rs 4000 
SELECT s_name,SUM(fee)
FROM Student NATURAL JOIN Stream
GROUP BY s_name
HAVING SUM(fee) > 4000
ORDER BY SUM(fee) desc;

7)Increase the fee by 500 for all students in the ‘PCMC’ stream.
UPDATE STUDENT
SET fee = fee + 500
WHERE s_id = (SELECT s_id FROM STREAM WHERE s_name = 'PCMC');

8)Update mobile number of student 'George Davis' to 9123456789.
UPDATE STUDENT
SET mobile = 9123456789
WHERE fname = 'George' AND lname = 'Davis';

9)Delete all students in the 'Arts' stream.
DELETE FROM STUDENT
WHERE s_id = (SELECT s_id FROM STREAM WHERE s_name = 'Arts');

10)Delete all students whose area starts with C and the first word has atleast 6 letters and ends with town.
DELETE FROM STUDENT
WHERE area LIKE 'C_____% Town';

Monday, 21 July 2025

GRADE 12 : PRACTICAL 14

 Create the below tables : 

DEPARTMENT : 


TEACHER: 


(Include the following constraints : 
> Check that 20<=age<=70
> Sex should take only M and F values) 


SOLUTION 
CREATE TABLE department (
         DeptName VARCHAR(20) PRIMARY KEY,
         HOD VARCHAR(30),
         RoomNo VARCHAR(10),
         Budget NUMERIC(7)
);
INSERT INTO department VALUES
         ('Computer', 'Dr. Sen', 'C101', 500000),
         ('History', 'Dr. Malhotra', 'H202', 300000),
         ('Math', 'Dr. Iyer', 'M303', 400000);
CREATE TABLE teacher (
    No INT PRIMARY KEY ,
    Name VARCHAR(20) NOT NULL,
    Age NUMERIC(2) CHECK (Age BETWEEN 20 AND 70),
    Department VARCHAR(20),
    DOJ DATE,
    Salary FLOAT,
    Sex VARCHAR(1) CHECK (Sex IN ('M', 'F')),
    FOREIGN KEY (Department) REFERENCES department(DeptName)
);
INSERT INTO teacher  VALUES
    (111,'Jugal', 34, 'Computer', '1997-01-10', 12000, 'M'),
    (222,'Sharmila', 31, 'History', '1998-03-24', 20000, 'F'),
    (333,'Sandeep', 32, 'Math', '1996-12-12', 30000, 'M'),
    (444,'Sangeeta', 35, 'History', '1999-07-01', 40000, 'F'),
    (555,'Rakesh', 42, 'Math', '1997-09-05', 25000, 'M'),
    (666,'Shyam', 50, NULL, '1998-06-27', 30000, 'M'),
    (777,'Shiv Om', 44, 'Computer', '1997-02-25', 21000, 'M'),
    (888,'Shalaka', 33, 'Math', '1997-07-31', 20000, 'F');

PRACTICE : 

1. Display the unique departments from Teacher Table.
SELECT DISTINCT Department 
FROM teacher 
WHERE Department IS NOT NULL;

2. Display the RECORD COUNT , DEPARTMENT COUNT(with repeats but without NULL)  in teacher table;
SELECT COUNT(*) AS RECORD_COUNT,COUNT(Department) AS DEPARTMENT_COUNT 
FROM teacher;

3.Display the number of teachers in each department.
SELECT Department, COUNT(*) AS Num_Teachers
FROM teacher
WHERE Department IS NOT NULL
GROUP BY Department;

4.Find the average salary of teachers in each department in increasing order of their average salaries.
SELECT Department, AVG(Salary) AS Avg_Salary
FROM teacher
WHERE Department IS NOT NULL
GROUP BY Department
ORDER BY AVG(Salary);

5.Show the names of departments having more than 2 teachers.
SELECT Department, COUNT(*) AS Teacher_Count
FROM teacher
WHERE Department IS NOT NULL
GROUP BY Department
HAVING COUNT(*) > 2;

6.Show department name, budget, and number of teachers in each department :
SELECT DeptName,Budget,COUNT(No) AS Teacher_Count
FROM department JOIN teacher ON DeptName = Department
GROUP BY DeptName,Budget;
or
SELECT DeptName,Budget,COUNT(No) AS Teacher_Count
FROM department , teacher WHERE DeptName = Department
GROUP BY DeptName,Budget;

7.Display the average salary per sex, in descending order of the average salary(Rounded to nearest hundreds)
SELECT Sex, round(avg(salary),-2) as Avg_Sal
FROM teacher
GROUP BY Sex
ORDER BY Avg_Sal desc;

8.Display the Name, Deparment and DOJ of the earliest joining teacher
SELECT Department, Name, DOJ
FROM teacher
WHERE DOJ = (
    SELECT MIN(DOJ)
    FROM teacher);

9.Increase the salary of all teachers in the 'Math' department by 10%
UPDATE teacher
SET Salary = Salary * 1.10
WHERE Department = 'Math';

10.Remove all teachers who are not assigned to any department.
DELETE FROM teacher
WHERE Department IS NULL;



Tuesday, 8 July 2025

Menagerie

CREATE DATABASE menagerie;
USE menagerie;
DROP TABLE IF EXISTS pet;

CREATE TABLE pet
(
  name    VARCHAR(20),
  owner   VARCHAR(20),
  species VARCHAR(20),
  sex     CHAR(1),
  birth   DATE,
  death   DATE
);
INSERT INTO pet VALUES('Fluffy','Harold','cat','f','1993-02-04',NULL);
INSERT INTO pet VALUES('Claws','Gwen','cat','m','1994-03-17',NULL);
INSERT INTO pet VALUES('Buffy','Harold','dog','f','1989-05-13',NULL);
INSERT INTO pet VALUES('Fang','Benny','dog','m','1990-08-27',NULL);
INSERT INTO pet VALUES('Bowser','Diane','dog','m','1979-08-31','1995-07-29');
INSERT INTO pet VALUES('Chirpy','Gwen','bird','f','1998-09-11',NULL);
INSERT INTO pet VALUES('Whistler','Gwen','bird',NULL,'1997-12-09',NULL);
INSERT INTO pet VALUES('Slim','Benny','snake','f','1996-04-29',NULL);
INSERT INTO pet VALUES ('Puffball','Diane','hamster','f','1999-03-30',NULL);

DROP TABLE IF EXISTS event;

CREATE TABLE event
(
  name   VARCHAR(20),
  date   DATE,
  type   VARCHAR(15),
  remark VARCHAR(255) DEFAULT NULL
);

INSERT INTO EVENT VALUES("Fluffy","1995-05-15","litter","4 kittens, 3 female, 1 male");
INSERT INTO EVENT VALUES("Buffy","1993-06-23","litter","5 puppies, 2 female, 3 male");
INSERT INTO EVENT VALUES("Chirpy","1999-03-21","vet","needed beak straightened");
INSERT INTO EVENT VALUES("Slim","1997-08-03","vet","broken rib");
INSERT INTO EVENT(name,date,type) VALUES("Bowser","1991-10-12","kennel");
INSERT INTO EVENT(name,date,type)  VALUES("Fang","1991-10-12","kennel");
INSERT INTO EVENT VALUES("Fang","1998-08-28","birthday","Gave him a new chew toy");
INSERT INTO EVENT  VALUES("Claws","1998-03-17","birthday","Gave him a new flea collar");
INSERT INTO EVENT VALUES("Whistler","1998-12-09","birthday","First birthday");

Monday, 30 June 2025

practical 15

 








CREATE TABLE STREAM (


    s_id INT PRIMARY KEY,

    s_name VARCHAR(20)

);


CREATE TABLE STUDENT (

    adno INT PRIMARY KEY,

    fname VARCHAR(20),

    lname VARCHAR(20),

    class VARCHAR(5),

    sec CHAR(1),

    fee INT,

    mobile BIGINT,

    area VARCHAR(30),

    s_id INT,

    FOREIGN KEY (s_id) REFERENCES STREAM(s_id)

);




INSERT INTO STREAM VALUES 
(10, 'PCMC'),
(20, 'PCMB'),
(30, 'PCBH'),
(40, 'HECA'),
(50, 'MECA'),
(60, 'Arts');

INSERT INTO STUDENT VALUES 
(1001, 'Ramesh', 'Babu', 'xii', 'a', 5000, 9988776655, 'Benson Town', 10),
(1002, 'Dipti', 'Rai', 'xii', 'b', 4500, 8877665599, 'Cooke Town', 20),
(1003, 'Rahul', 'Pai', 'xii', 'c', 4000, 7766559988, 'Fraser Town', 30),
(1004, 'Shruthi', 'Saravanan', 'xii', 'c', 4000, 6655998877, 'Benson Town', 30),
(1005, 'George', 'Davis', 'xi', 'a', 4500, 5599887766, 'Cooke town', 10),
(1006, 'Tinu', 'Anna', 'xi', 'b', 4200, 9988776611, 'Benson Town', 20),
(1007, 'Abrar', 'Sultan', 'xi', 'c', 4100, 9988776622, 'Cooke town', 40),
(1008, 'Iffath', 'Khan', 'xii', 'a', 5000, 9988776633, 'Fraser Town', 10),
(1009, 'Hansika', 'Singh', 'xii', 'b', 4500, 9988776644, 'Cleveland Town', 20),
(1010, 'Kailash', 'Dharyanani', 'xii', 'c', 4000, 9988776633, 'Richard Town', 50);


Thursday, 19 June 2025

GRADE 12 : PRACTICE

 Create the below tables : 

DEPARTMENT : 



TEACHER: 


(Include the following constraints : 
> DeptName is PK in Department Table
> No is PK in Teacher table
> Department is a foreign key in TEACHER
> Check that 20<=age<=70
> Sex should take only M and F values) 


SOLUTION 

 CREATE TABLE department (

         DeptName VARCHAR(20) PRIMARY KEY,

         HOD VARCHAR(30),

         RoomNo VARCHAR(10),

         Budget NUMERIC(7)

     );


INSERT INTO department VALUES

         ('Computer', 'Dr. Sen', 'C101', 500000),

         ('History', 'Dr. Malhotra', 'H202', 300000),

         ('Math', 'Dr. Iyer', 'M303', 400000);


CREATE TABLE teacher (

    No INT PRIMARY KEY ,

    Name VARCHAR(20) NOT NULL,

    Age NUMERIC(2) CHECK (Age BETWEEN 20 AND 70),

    Department VARCHAR(20),

    DOJ DATE,

    Salary FLOAT,

    Sex VARCHAR(1) CHECK (Sex IN ('M', 'F')),

    FOREIGN KEY (Department) REFERENCES department(DeptName)

);


INSERT INTO teacher  VALUES

    (111,'Jugal', 34, 'Computer', '1997-01-10', 12000, 'M'),

    (222,'Sharmila', 31, 'History', '1998-03-24', 20000, 'F'),

    (333,'Sandeep', 32, 'Math', '1996-12-12', 30000, 'M'),

    (444,'Sangeeta', 35, 'History', '1999-07-01', 40000, 'F'),

    (555,'Rakesh', 42, 'Math', '1997-09-05', 25000, 'M'),

    (666,'Shyam', 50, NULL, '1998-06-27', 30000, 'M'),

    (777,'Shiv Om', 44, 'Computer', '1997-02-25', 21000, 'M'),

    (888,'Shalaka', 33, 'Math', '1997-07-31', 20000, 'F');


PRACTICE : 

List all teacher names and their departments.

select name,department from teacher;


Display all female teachers.

Select name from teacher where sex='f';


Find teachers who joined before 1998.

Select * from teacher where doj < '1998-01-01';


Show names of teachers with salary above 25,000.

select name,salary from teacher where salary>25000;


List all teachers who do not have a department.

select * from teacher where department is null;


Display the non computer teachers.

select * from teacher where department != 'computer' or department is NULL;


Display the Count of all teachers teachers.

select count(name) as TeacherCount from teacher;


Display the total salary of all teachers.

select sum(Salary) as TotalSalary from teacher;


Display the maximum age among the teachers.

select max(age) as MaxAge from teacher;


Display the earliest DOJ.

select min(doj) as EARLIESTDOJ from teacher;


Display teachers sorted by salary in descending order.

select * from teacher order by salary desc;


List teacher names and their ages who are above 40.

select name,age from teacher where age>40;


Find the average salary of all teachers.

select avg(salary) as AVERAGE_SALARY from teacher ;


Find the average salary of all male teachers.

select avg(salary) from teacher where sex='m';


Find the youngest teacher. 

select * from teacher order by age limit 1;

select * from teacher where age = (select min(age) from teacher);


Find the teacher with the maximum salary.

select * from teacher where salary = (select max(salary) from teacher);


List all departments and their HODs.

 select deptname,hod from department;


Display departments with a budget over ?4,00,000.

select * from department where budget>400000;


Show department names and room numbers.

select deptname,roomno from department


Find the department with the lowest budget.

select deptname,budget from department 

where budget= (select min(budget) from department);


Display the total budget of all departments.

select sum(budget) from department;


List departments in alphabetical order.

select deptname from department order by deptname;


List names that start with s

select name from teacher where name like 's%';


List names that contain and a or an e

select name from teacher where name like '%a%' or '%e%';


List names that contain an a and an e

select name from teacher where name like '%a%' and '%e%';


List names that contain 2 a's

select name from teacher where name like '%a%a%';


List names that contain 'sh' in their name

select name from teacher where name like '%sh%';


List names that have 3rd letter as 'a'

select name from teacher where name like '__a%';


List names that have exactly one letter as 'a'

select name from teacher where name like '%a%' and name not like '%a%a%' ;


List the 8 letter names that end with a.

select name from teacher where name like '_ _ _ _ _ _ _ a';


Display the average salary of teacher : 

select avg(salary) from teacher;


 Display the department name and the corresponding average salaries:

select department,avg(salary) from teacher group by department;


Display the non-null department name and the corresponding average salaries:

select department,avg(salary) 

from teacher 

where department is not null 

group by department;


Display the non-null department name and the corresponding average salaries, in increasing order of their average salaries.

select department,avg(salary) as AvgSal 

from teacher 

where department is not null 

group by department 

order by avgsal;


Display the average salary per sex, in descending order of the average salary

select sex, avg(salary)

from teacher

group by sex

order by avg(salary) desc;



Thursday, 12 June 2025

Revision worksheet

1. This method returns an integer that specifies the current position of the file object.
a) seek() b) load() c) position() d) tell()

2.Answer the below ASSERTION(A) AND REASONING(R) based questions. (5x1=5)
Mark the correct choice as :
(a)Both A and R are true and R is the correct explanation for A.
(b)Both A and R are true and R is not the correct explanation for R.
(c)A is true but R is false.
(d)A is false but R is true.
Assertion (A): For a binary file opened using 'rb' mode, the pickle.dump() displays an error. 
Reason (R): The pickle.dump() method is used to read from a binary file. 

3. Predict the output of :
myfile=open('rhyme.txt','w+')
myfile.write("""Hot cross buns
Hot cross buns
One a penny
Two a penny
Hot cross buns""")
myfile.seek(0)
s=myfile.read(5) ; print(s)
s=myfile.readline(5) ; print(s)
s=myfile.read(5) ; print(s)
s=myfile.readlines() ; print(s)
myfile.close()

4. What will be the output of the following code ?
a) def   fun1( ):
            x=15
            print(x)
   x = 12
   fun1( )
   print(x)
 b)def   test( ):
        print(age)
        age=17
  age = 16
  test( )
  print(age)
c) def grade(a,b,c):
       print(b,a,c)
   a,b,c=9,5,2
   grade(c,a,b)
   print(b,c,a)

5. Which of the following is not a correct statement for binary files?
a. Easy for carrying data into buffer    b. Much faster than other file systems
c. Characters translation is not required d. Every line ends with new line character ‘\n’

6. To read at the most 2 bytes of a line from a file object infile, we use _________
a. infile.read(2) b. infile.readline() c. infile.readline(2) d. infile.readlines(2)

7.Write a program to accept five sports name from the user into a list sname and write them in a file “sports.txt”.Make sure that they’re written on separate lines in the file. Further , display the contents of the file.
8. Write a function that accepts two parameters : a dictionary and a number; and prints only the keys that have values more than the passed number.

9. Rewrite the following code snippet to accept the value of a and to pass it to a function to compute the following. The default value of a should be 25,if no argument has been sent. Also, replace the while loop with a for loop. Predict the output if the value entered by the user is 50.
  a=25
while a < 500:
print a
a = a + 25

10.a)Predict the output for the following python program.  Fill in the blank to ensure that no  new local variable wand is used in the function magic().Predict the new output.
wand=25
def magic(w):
__________________
    wand =w*4
    print("wand : ",wand)
print("wand : ",wand)
magic(wand)
print("wand : ",wand)  

b) What is the output of ?
total=0 
def add(a,b): 
    global total
    print(total)  
    total=a+b 
    print(total)
add(6,6) 
print(total)

11. Read the code given below and answer the questions
f1=open('main.txt','w+') 
f1.write('Bye') 
f1.close() 
If the file contains 'Good ' before execution(cursor on the same line), what will be the content of the file after execution of the code ?

12. Find output generated by the following code:
Str='Computer'
print(Str[-2::-1])
Str=Str[-6:6]*2
print(Str)

13.Answer the following:
i) By default python names the segment with top-level statement as __________________
a) def main() b) main() c) _ _main_ _ d) _main_

ii)Suppose lst is [2,4,6,8,10,12,24], What is  the list after lst.pop(3)?
a)[2,4,6,8] b)[8,10,12,24] c)[2,4,8,10,12,24] d)[2,4,6,10,12,24]

iii)What will happen if you try to open a binary file using a text ?
i) Default value ii) Advance value iii)Garbage value iv)Parameter value

14. What is the output of the following code? 
print("We don\t talk any more")
print(len("We don\t talk any more"))
print("We don\t talk any more"[5:10])
b)


15. Write a function called authenticate(users,loginid,password) which takes following 3 parameters:
> users : a dictionary storing login ids and corresponding password values
> loginid : a string for a login name and 
> password : a string for a password

The function should do the following: 
i) if the user exists and the password is correct for the given loginid, it should print ‘Access granted
ii) if the user exists and the password is incorrect for the given loginid , it should print ‘Incorrect password’.
iii)If the user does not exist for the given loginid , it should print ‘wrong credentials’

16. Write a program to read following details (as long as the user wants) of sports’ performance (sport, competitions, prizes-won) of your school and store into a csv file delimited with tab character, where :
sport => sports name the school participated in
competitions => no. Of interschool competitions participated in
prizes-won=> no. Of competitions won

17. Write a program that copies a  text file ‘source.txt’ onto ‘target.txt’ barring the lines starting with an ‘@’ sign.

18. A binary file "Student.dat" has the structure :
{'stud_id':int, 'stud_name': string,  'percentage': float}
Write a menu driven program using functions for the following:
a> Accept the details of a student.
b> Display the details of all students and the average percentage in tabular format
c> Display the name and marks of students scoring 75% and above

Wednesday, 4 June 2025

GRADE 12 PRACTICAL 13

'''A stack named StuStack contains records of students.Each record is represented as a list,eg [101, 'Ravi', 87.5]

Write the following user-defined functions :

(i) pushStu(StuStack,StuList):

this takes StuStack and a list of students as arguments, and pushes the list into the stack.

(ii) popStu(StuStack):

This function pops the topmost student record from the stack and returns it. If empty, display the message

"Stack Underflow" and return None.

(iii) display(StuStack):

This function should display the student by popping it one by one. Also display the record with the highest marks. If the stack is empty, display "No student records".

'''


StuStack=[]


def menu():

    while True:

        ch=int(input("""MENU :

1.PUSH

2.POP

3.DISPLAY

4.EXIT"""))

        if ch==1:

            StuList=[]

            n=int(input("Enter no of records you want to add : "))

            for i in range(n):

                stuid=int(input('Enter student id : '))

                name=input("Enter name : ")

                marks=float(input('Enter marks : '))

                l=[stuid,name,marks]

                StuList.append(l)

            pushStu(StuStack,StuList)

        elif ch==2:

            rec=popStu(StuStack)

            if rec:

                print(rec)

            else:

                print('Empty')

        elif ch==3:

            display(StuStack)

        else:

            break


def pushStu(StuStack,StuList):

    for i in StuList:

        StuStack.append(i)


def popStu(StuStack):

    if len(StuStack)>0:

        return StuStack.pop()

    else:

        print('STACK UNDERFLOW')

        return None

    

def display(StuStack):

    maxx=0

    if len(StuStack)==0:

        print('Empty Stack')

        return

    while StuStack:

        rec = StuStack.pop()

        print(rec)

        if rec[2]>maxx:

            maxx=rec[2]

            Student=rec

        

    print('Student with maximum marks : ',Student)


menu()

    

    



Tuesday, 3 June 2025

GRADE 12 - PRACTICAL 12

'''GRADE 12: PRACTICAL 12

Create a list Library to implement a STACK data structure

in Python. The Library stack can hold a maximum of 5 records,

each representing a book. Each book is represented as :

{"BookID": <int>, "Title": <str>,

"Author": <str>,"Year": <str>}

Write a menu-driven program to perform :

a) push- Add a new book record to the stack.

b) pop- Delete the topmost book record from the stack.

c) display - To display all book records

d) peek- To view the topmost record of the stack

Handle Underflow and Overflow conditions for the stack .

'''

Library=[]

limit=5

def menu():

    while True:

        ch=int(input("""MENU:

1.PUSH

2.POP

3.DISPLAY

4.PEEK

5.EXIT

"""))

        if ch==1:

            bid=int(input("Enter book id "))

            title=input("enter title")

            auth=input("Enter author")

            year=input("Enter year")

            book={"BookID":bid, "Title":title,

"Author":auth,"Year":year}

            push(Library,book)

            

        elif ch==2:

            book=pop(Library)

            if book:

                print('Popped record : ',book)

                        

        elif ch==3:

            display(Library)


        elif ch==4:

            book=peek(Library)

            if book:

                print('Peekeed record : ',book)

            

        else:

            break


  

def push(Library,book):

    if len(Library)<limit:

        Library.append(book)

        print('Pushed record : ',book)

    else:

        print('OVERFLOW')



def pop(Library):

    if len(Library)>0:

        return Library.pop()

    else:

        print('UNDERFLOW')

        return None


def display(Library):

    print('Contents of Library')

    if len(Library)>0:

        for i in Library[::-1]:

            print(i)

    else:

        print('EMPTY')


def peek(Library):

    if Library:

        return Library[-1]

    else:

        print('UNDERFLOW')

        return None



menu()

            

        

    


Thursday, 29 May 2025

GRADE 12 - PRACTICAL 11 - BINARY FILES

"""WAPP to demonstrate the following optionsby creating different methods using binary files for a hospital management application :

(i) adding records of the structure :  {'pid':<str>,'pname':<str>,'diag':<str>,'fees':<int>}

(ii)reading and displaying all the records in a

tabular format

(iii)searching and displaying patients who have 'corona'

(iv)update the diagnosis of the given patient id

(Display appropriate messages if patient not found or file not found.)

"""



import pickle def menu(): while True: print("""Menu 1)Enter patient details 2)Display patient details 3)Search 4)Update 5)Exit'""") ch = int(input("Enter your choice : ")) if ch==1: accept() elif ch==2: display() elif ch==3: search() elif ch==4: update() else: break def accept(): with open('Diagnostics.dat','ab') as f: pid=input('Enter patient id : ') pname=input(("Enter patient's name : ")) diag = input('Enter patient diagnosis : ') fee = int(input('Enter patient fee :')) d={'pid':pid,'pname':pname,'diag':diag,'fee':fee} pickle.dump(d,f) def display(): try: with open('Diagnostics.dat','rb') as f: print('pid'.ljust(15),'pname'.ljust(20),'diagnosis'.ljust(15),'fees') while True: rec = pickle.load(f) print(rec['pid'].ljust(15),rec['pname'].ljust(20),rec['diag'].ljust(15),rec['fees']) except FileNotFoundError: print('Sorry, File not found') except EOFError: pass except Exception as e: print("Unexpected error : ",e) def search(): try: with open('Diagnostics.dat','rb') as f: print("Patient details with corona : ") while True: rec = pickle.load(f) if rec[2] == "corona": for i in rec: print(str(i).ljust(15),end='') print() except FileNotFoundError: print('Sorry, File not found') except EOFError: pass except Exception as e: print("Unexpected error : ",e) def update(): try: with open('Diagnostics.dat','rb') as f: pid=input("Enter pid of patient to be updated : ") l=[] found=False while True: rec = pickle.load(f) if rec[0] == pid: rec[2]=input("Enter new diagnosis") found=True print("Record updated successfully") l.append(rec) if found== False: print("Required record not found") with open('Diagnostics.dat','wb') as f: for rec in l: pickle.dump(rec,f) except FileNotFoundError: print('Sorry, File not found') except EOFError: pass except Exception as e: print("Unexpected error : ",e) menu()

Wednesday, 21 May 2025

GRADE 12: PRACTICAL 10: CSV FILES

''' Write a menu-driven program to perform the following

functions on a csv file ‘Cricket.csv’

i) Accept details of n players and write into the file.

The header will be:  [Player ID, Player Name, Team, Runs Scored]

ii) Display the id, names and runs of all players who have scored

century. Also display the average of such players.

iii) Search for a player by name and display their details 

if found, else show "Player not found."

iv) Update the runs scored by a player (given their Player ID)

If found, ask for new runs and update the file.

'''

import csv


def menu():

    while True :

        ch=int(input("""MENU :

1.Accept

2.Display

3.Search

4.Update

5.Exit

"""))

        if ch==1:

            accept()

        elif ch==2:

            display()

        elif ch==3:

            search()

        elif ch==4:

            update()

        else:

            break


def accept():

    n=int(input("Enter no of records : "))

    with open("cricket.csv","a",newline="") as f:

        writer=csv.writer(f)

        if f.tell()==0:

            writer.writerow(['Player ID', 'Player Name',' Team', 'Runs Scored'])

        for i in range(n):

            pid = input("Enter Player ID: ")

            name = input("Enter Player Name: ")

            team = input("Enter Team Name: ")

            runs = int(input("Enter Runs Scored: "))

            writer.writerow([pid, name, team, runs])


def display():

    with open("cricket.csv","r")as f:

        reader = csv.reader(f)

        title=next(reader)

        high=[]

        print('ID'.ljust(15),'NAME'.ljust(15),'RUNS'.ljust(15))

        for a,b,c,d in reader:

            if int(d)>=100:

                high.append(int(d))    

                print(a.ljust(15),b.ljust(15),d.ljust(15))

        if len(high)==0:

            print( 'No such records')

        else:

            print('Average of the top batsmen : ', sum(high)/len(high))

            

                  

def search():

    name=input("Enter player name to be searched : ")

    with open("cricket.csv","r") as f:

        reader=csv.reader(f)

        header=next(reader)

        for i in reader:

            if i[1]==name:

                print("Player found : ",i)

                break

        else:

            print("Player not found ")


def update():

    with open('Cricket.csv','r') as f:

        c=csv.reader(f)

        l=list(c)

        pid=input("enter player id to be updated")

        for i in l[1:]:

            if pid==i[0]:

                i[3]=int(input("Enter new no of runs"))

                break

        else:

            print("player not found")

    with open('Cricket.csv','w',newline='') as f:

        c=csv.writer(f)

        c.writerows(l)

        


menu()


Wednesday, 9 April 2025

GRADE 12 : PRACTICAL 9 : BINARY FILES

 '''Write a program to create a binary file Course.dat

for DIIT training centre to store course information of

all the computer language courses held at their institute.

Each record should be of the form :

[ course_id, course_name, duration(in months), fee].

The program should include the following functionalities:

i) Append new course records to the binary file.

ii) Display all course records from the binary file.

iii) Search for a course by course_id and display its

details, otherwise display an error.

iv) Calculate the average fees of the courses at DIIT

centre.

v) Increase the fees of each course by 10%'''

import pickle

def menu():

    while True :

        ch=int(input("""MENU :

1) ADD record

2) DISPLAY records

3) SEARCH for record

4) CALCULATE the average fees of the course

5) UPDATE record

6) EXIT

YOUR CHOICE : """))

        if ch==1:

            add()

        elif ch==2:

            display()

        elif ch==3:

            search()

        elif ch==4:

            calculate()

        elif ch==5:

            update()

        else:

            break


def add():

    with open('course.dat','ab') as f:

        n=int(input("Enter number of records : "))

        for i in range(n):

            c_id=int(input("Enter course id : "))

            c_name=input("Enter course name : ")

            duration=int(input("Enter the course duration(months) : "))

            fee=int(input("Enter the fees : "))

            rec=[c_id,c_name,duration,fee]

            pickle.dump(rec,f)


def display():

    try:

        with open('course.dat','rb') as f:

            while True:

                rec=pickle.load(f)

                print(rec)

    except EOFError:

        pass

    except Exception as e:

        print(e)


def search():

    c_id=int(input("Enter course id : "))

    try:

        with open('course.dat','rb') as f:

            while True:

                rec=pickle.load(f)

                if c_id==rec[0]:

                    print(rec)

                    break

    except EOFError:

        print(f"Course no {c_id} not found")

    except Exception as e:

        print(e)


def calculate():

    fees=[]

    try:

        with open('course.dat','rb') as f:

            while True:

                rec=pickle.load(f)

                fees.append(rec[3])

    except EOFError:

        avg=sum(fees)/len(fees)

        print(f"Average fees ={avg}")

    except Exception as e:

        print(e)



def update():

    l=[]

    try:

        with open('course.dat','rb') as f:

            while True:

                rec=pickle.load(f)

                rec[3]=rec[3]*1.1

                l.append(rec)                

    except EOFError:

        pass

    except Exception as e:

        print(e)

    with open('course.dat','wb') as f:

        for rec in l :

            pickle.dump(rec,f)

    print("Records have been updated ")

    display()

    

menu()