ACADEMIC YEAR: 2024-25
Name : Yashmit
Class : XII A1
Roll No. : 3
Subject Teacher : Priyanka Bisht Ma’am
School : Delhi Jain Public School
1
TITLE Page
No.
Chapter-1 Python Revision Tour- I 3-4
Chapter-2 Python Revision Tour-II 5-6
Chapter-3 Working With Functions 7-9
Chapter-4 File Handling 10-12
Chapter-7 Data Structures 13-15
Chapter-11 Simple Queries in SQL 16-26
Chapter-14 Interface Python With MySQL 27-37
2
Chapter-1
Q1. Write a program to print one of the words negative, zero, or positive,
according to whether the variable x is less than zero, zero, or greater than
zero, respectively.
Ans. x=int(input("Enter any number :"))
if x<0:
print("Negative")
elif x==0:
print("Zero")
else:
print("Positive")
Output:
Q2. Write a python program that accepts two integers from the user and
prints a message saying if first number is divisible by second number or if it
is not.
Ans. num1=int(input("Enter a First number :"))
num2=int(input("Enter a Second number :"))
if num1%num2==0:
print(num1," is divisible by a ",num2)
else:
print(num1," is not divisible by a ",num2)
3
Output:
Q3. Write a program that prints on two columns- table that
helps converting miles into kilometres.
Ans. M=1
K=1.6934
print("Miles Kilometres")
print(M,"\t",K)
for i in range(10,101,10):
print(i,"\t",i*K)
Output:
Chapter-2
Q1. Write a program that takes any two lists L and M of the same size and
adds their elements together to form a new list N whose elements are sums
of the corresponding elements in L and M. For instance, if L=[3,1,4] and
M=[1,5,9], then N should equal [4,6,13].
Ans. L=eval(input("Enter first list :"))
M=eval(input("Enter second list :"))
N=[]
for i in range(len(L)): #Both Lists are of same size
Sum=L[i]+M[i]
[Link](Sum)
print("New List :",N)
Output:
Q2. Write a program that creates a tuple storing first 9 terms of Fibonacci
Series.
Ans. Tuple=(0,1,1)
for i in range(6):
term=Tuple[i+1]+Tuple[i+2]
Tuple+=(term,)
print("First Nine Terms of Fibonacci Series :",Tuple)
5
Output:
Q3. Write a program to create a dictionary containing names
of competition winner students as keys and number of their
wins as values.
Ans. n=int(input("How many students ? "))
CompWin={}
for i in range(n):
key=input("Enter name of the student :")
value=int(input("Enter number of competition wins :"))
CompWin[key]=value
print("Created Dictionary is ")
print(CompWin)
Output:
Chapter-3
Q1. Write a function to calculate volume of a box with appropriate default
values for its parameters. Your function should have the following input
parameters :
a) Length of the box ;
b) Width of the box ;
c) Height of the box,
Ans. def volume(length=5,width=4,height=2):
return length*width*height
A=volume()
print("Volume of the given box with default values is ",A)
B=volume(2,2,2)
print("Volume of the given box is",B)
Output:
Q2. Write a function that receives two string arguments and checks whether
they are same-length strings (returns True in this case otherwise False.
Ans. def check(S1,S2):
if len(S1)==len(S2):
7
return True
else:
return False
S1=input("Enter a string :")
S2=input("Enter another string :")
A=check(S1,S2)
print(A)
Output:
Q3. Write a program that receives two numbers in a function and returns
the results of all arithmetic operations (+,-,*,/,%) on these numbers.
Ans. def Calc(num1,num2):
return num1+num2,num1-num2,num1*num2,num1/num2,num1%num2
num1=int(input("Enter first number :"))
num2=int(input("Enter second number :"))
A,S,M,D,R=Calc(num1,num2)
print("Sum of these two numbers :",A)
print("Difference of these two numbers :",S)
print("Multiplication of these two numbers :",M)
print("Division of these two numbers :",D)
print("Modulo of these two numbers :",R)
8
Output:
9
Chapter-4
Q1. Write a program to get roll numbers, names and marks of the students of a class (get from
user) and store these details in a file called “[Link]”.[txt]
Ans. num=int(input("How many students are there in the class ?
:")) File=open("[Link]","w")
for i in range(num):
print("Enter details of the student",(i+1),"below")
Roll=int(input("Roll No. :"))
name=input("Name :")
marks=float(input("Marks :"))
rec=str(Roll)+","+name+","+str(marks)+"\n"
[Link](rec)
[Link]()
Output:
10
Q2. Write a program to a binary file called “[Link]” and write into it the
employee details of some employees, available in the form of
dictionaries.[bin]
Ans. import pickle
emp1={"Empno":1201,"Name":"Raman","Age":20,"Salary":50000}
emp2={"Empno":1211,"Name":"Alexander","Age":25,"Salary":60000}
emp3={"Empno":1251,"Name":"Ramesh","Age":30,"Salary":30000}
emp4={"Empno":1291,"Name":"Mohan","Age":29,"Salary":40000}
File=open("[Link]","wb")
[Link](emp1,File)
[Link](emp2,File)
[Link](emp3,File)
[Link](emp4,File)
print("File has been successfully created.")
[Link]()
Output:
Q3. Write a program to create a CSV file to store student data
(Rollno.,Name,Marks). Obtain data from user and write 2 records into the
file.[CSV]
Ans. import csv
File=open("[Link]","w")
Stu=[Link](File)
[Link](["Roll no.","Name","Marks"])
for i in range(2):
print("Students record",(i+1))
11
roll=int(input("Enter Roll no. :"))
name=input("Enter Name :")
marks=float(input("Enter Marks :"))
Sturec=[roll,name,marks]
[Link](Sturec)
[Link]()
Output:
12
Chapter-7
Q1. Alam has a list arr containing ten integers. You need to help him create
a program with separate user defined function named PUSH(arr,stk). Create
a stack and push those elements from list which are at even places.
Ans. arr=[10,20,30,40,50,60,70,80,90,100]
stk=[]
def PUSH(arr,stk):
for i in range(0,len(arr),2):
[Link](arr[i])
PUSH(arr,stk)
print("your stack is",stk)
Output:
Q2. Vishal has created a list Arr with some element. Help him to create
user defined function to perform the following tasks:
Create a stack after checking element if it is even, multiply it by 2, and if
the element is odd then multiply by it 3. Pop and display the contents of the
stack.
Ans. arr=[10,15,23,96,45,17,28,13,48]
stk=[]
13
def PUSH(arr,stk):
for i in arr:
if i%2==0:
num=i*2
[Link](num)
else:
num=i*3
[Link](num)
def POP(stk):
if stk!=[]:
a=[Link]()
print(a)
PUSH(arr,stk)
print("Created Stack:-",stk)
while True:
if stk!=[]:
POP(stk)
else:
break
Output:
14
Q3. A list contains record of customers: [cust, roomtype].
Write a function in python to perform given operations on stack named Hotel:
i) PUSH_CUST()- customers in Delux Room Type.
ii) POP_CUST()- Pop names .
Also, Display “underflow” when there are no customers in
Stack. Ans:
Customer=[["ramesh","delux"],["suresh","Standard"],["mukesh","delux"],[
" ganesh","delux"],["mahesh","Economy"]]
hotel=[]
def PUSH_CUST():
for i in Customer:
if i[1]=="delux":
[Link](i[0])
def POP_CUST():
if hotel==[]:
return "Underflow"
else:
return [Link]()
PUSH_CUST()
print("created hotel data:-",hotel)
while True:
if hotel==[]:
break
else:
print(POP_CUST())
Output:
15
Chapter-11
Q1. Consider the following tables WORKER and PAYLEVEL .Write
SQL commands for the following statements.
Table : WORKER
Table : PAYLEVEL
(i) To display the details of all WORKERs in descending order of DOB. (ii)
To display the content of all the WORKERs table, whose DOB is in
between ’19-JAN-1984’ and ’18-JAN-1987’.
(iii) To display NAME and PAY of those workers whose PLEVEL are the
same and ECODE is less than 13.
(iv) To display PLEVEL and ALLOWANCE of those whose PAY is > 6000. (v)
To add primary key in table PAYLEVEL.
Ans: CREATION
create table WORKER
(ECODE integer,
NAME char(30),
DESIG char(30),
PLEVEL char(30),
DOJ date,
DOB date);
create table PAYLEVEL
(PLEVEL char(30),
PAY integer,
ALLOWANCE integer);
16
INSERTION
insert into worker values
(11,'RadheShyam','Supervisor','P001','13September2004','23August1
9 81')
insert into worker values (12,'Chander Nath','Operator','P003','22-
Feb-2010','12-Jul-1987')
insert into worker values (13,'Fizza','Operator','P003','14-Jun
2009','14-oct-1983')
insert into worker values (15,'Ameen Ahmed','Mechanic','P002','21-
Aug-2006','13-Mar-1984')
insert into worker values (18,'Sanya','Clerk','P002','19-Dec-2005','09-
Jun-1983')
insert into PAYLEVEL values ('P001',26000,12000)
insert into PAYLEVEL values ('P002',22000,10000)
insert into PAYLEVEL values ('P003',12000,6000)
(i) select * from worker
order by DOB desc
Output:
(ii) select * from worker
where DOB between '19JAN1984' and '18JAN1987';
Output:
17
(iii) select name,pay from worker , paylevel
where ecode<13 and [Link]=[Link];
Output:
(iv) select plevel,allowance from paylevel
where pay>6000;
Output:
(v) Alter table PAYLEVEL
add primary key as PLEVEL;
Q2. Write SQL queries for (a) to (e) based on the tables PASSENGER and
FLIGHT given below:
Table : PASSENGER Table : FLIGHT
(a)
Write a query to change the fare to 6000 of the flight whose FNO is
F104.
18
(b) Write a query to display the total number of MALE and FEMALE
PASSENGERS.
(c) Write a query to display the NAME , corresponding FARE and
F_DATE of all PASSENGER who have a flight to START2 and
DELHI.
(d) Write a query to change the END1 to “CHANDIGARH” of flight
whose FNO is F102.
(e) Write a query to delete the records of flight which end at MUMBAI.
Ans:
(a) Update FLIGHT
set Fare=6000
where FNO='F104';
Output:
(b) select gender,count(*) from PASSENGER
group by gender;
Output:
(c) Select name , fare ,f_date from PASSENGER P,FLIGHT F
where [Link]=[Link] and START2='DELHI';
Output:
19
(d) Update FLIGHT
set END1='CHANDIGARH'
where FNO='F102';
Output:
(e) Delete from FLIGHT
where end1='MUMBAI';
Output:
Q3. Consider the following DEPT and WORKER tables. Write SQL
queries for (i) to and (iv) find outputs for SQL queries (v) to (viii): Table :
DEPT Table : WORKER
Note:- DOJ refers to date of
joining and DOB refers to date of birth of workers.
(i) To display Wno, Name, Gender from the table WORKER in descending
order of Wno.
20
(ii) To display the Name of all the FEMALE workers from the table
WORKER.
(iii) To display the Wno and name of those workers from the table WORKER.
Who are born between ‘01-01-1987’ and ’01-12-1991’.
(iv) To count and display MALE workers who have joined after ’01-01-1986’. (v)
To display the Gender along with their Name from the table WORKER.
Ans:
(i) select Wno , Name, Gender from WORKER
order by Wno desc;
Output:
(ii) select Name from WORK
where Gender='FEMALE';
Output:
(iii) select Wno,Name from WORKER
where DOB between '1january1987' and ‘1december1991';
21
Output:
(iv) select count(*) from WORKER
where Gender ='MALE' and DOJ>'1january1986';
Output:
(v)select Gender,Name from WORKER;
Output:
Q4. Given the flowing tables for a database library:
Table : BOOKS
22
Table : ISSUED
(a) To show Book_name, author_name and price of books of first publ.
publishers.
(b) To list the names from books of text type
(c) To display the names and price from books in ascending order of
their price
(d) To increase the price of all books of epb by 50
(e) To display the book_id, book_name and quantity_issued for all
books which have been issued (the query will require contents from
both the table).
Ans.
(a) select Book_name,author_name,price from book
where publishers='FIRST PUBL';
Output:
(b) select BOOK_NAME from book
where type='TEXT';
Output:
23
(c) select book_name,price from book
order by price;
Output:
(d) Update book
set price=price+50
where publishers='EPB';
Output:
(e) select book.book_id,book_name,quantity_issued
from book,issued
where book.book_id=Issued.book_id
Output:
24
Q5. In a database, there are two tables in below:
Table : EMPLOYEE Table : JOBS
Write SQL Queries For The Following:
(i) To display employeeids, name of employees, job with
corresponding job titles.
(ii) To display names of employees, sales and corresponding job titles
who have achieved sales more than 1300000.
(iii) To display names and corresponding job titles of those employees
who have ‘SINGH’ (anywhere) in their names.
(iv) Add primary key in the table EMPLOYEE.
(v) Write SQL command to change the JOBID to 104 of the employees
with id as E4 in the table ‘EMPLOYEE’.
Ans.
(i) select EMPLOYEEID ,NAME,JOBTITLE from
EMPLOYEE,JOB
where [Link] = [Link] ;
Output:
25
(ii) select NAME ,SALES,JOBTITLE from EMPLOYEE , JOB where
SALES > 1300000 and [Link] = [Link]; Output:
(iii) select NAME ,JOBTITLE from EMPLOYEE , JOB
where NAME like '%SINGH%' and [Link]= [Link];
Output:
(iv) Alter table EMPLOYEE
ADD primary key (EMPLOYEEID);
Output:
(v) update EMPLOYEE
set JOBID = 104
where EMPLOYEEID = 'E4';
Output:
26
Chapter-14
Q1. Manya wants to write a program in python to insert the following
record in the table named student15 in MySQL database, TEST:
∙ admn_no(admn_no)-Integer
∙ name-char(15)
∙ subject-char(15)
∙ marks-float
Note: The following to establish connectivity between Python and
MySQL: ∙ Username-root
∙ Password-tiger
∙ Host-localhost
The values of field admnno, name, subject and marks has to accept
from the user. Help Manya to write the program in Python.
Ans.
import [Link] as SQL
mycon=[Link]
(host="localhost",user="root",password="",database='test',charset='
u tf8')
cur=[Link]()
[Link]("create table student15(admn_no integer,name
char(15),sub1 char(12),sub2 char(12),marks float)")
[Link]("insert into student15
values(1234,'Priya','English','Pcm',20)")
[Link]("insert into student15
values(1235,'Manya','English','Pcm',22)")
27
[Link]("select * from student15")
p=[Link]()
[Link]()
for i in p:
print(i)
Output:
Q2. The code given below reads the following record from the table named
student15 and displays update the marks of admn_no [Link] the
following to establish connectivity between Python and MySQL:
∙ Username is system
∙ Password is tiger
∙ The table exists in a MYSQL database named TEST.
Ans.
import [Link] as SQL
mycon=[Link](host="localhost",user="system
",password="",database ='test',charset='utf8')
cur=[Link]()
[Link]("update student15 set Marks =17 where admn_no=1234")
[Link]("select * from student15")
p=[Link]()
[Link]()
for i in p:
print(i)
28
Output:
='utf8')
Q3. The code given below deletes the record from the table student15
which contain the following structure:
∙ Admn_no(admn no)-Integer
∙ name-char(15)
∙ subject-char(15)
∙ marks-float
Note:- the following to establish connectivity between Python and
MySQL: ∙ Usernsme is system
∙ Password is tiger
∙ The table exists in a MySQL database named test.
Ans.
import [Link] as SQL
mycon=[Link](host="localhost",user="system
",password="",database ='test',charset='utf8')
cur=[Link]()
[Link]("delete from student15 where admn_no=1235")
[Link]("select * from student15")
p=[Link]()
[Link]()
for i in p:
print(i)
29
Output:
Q4. The code given below inserts the following record in the table
student: Roll No – integer
Name – string
Class – integer
Marks - integer
Note:-The following to establish connectivity between Python and
MySQL: ❖Username is root
❖Password is tiger
❖The table exists in a MySQL database named school.
❖The details (Roll_No, Name, Class and Marks) are to be accepted from
the user.
Write the following missing statements to complete the code:
[Link] form the cursor object.
[Link] execute the command that inserts the record in the table
Student.
[Link] add the record permanently in the database.
import [Link] as mysql
def sql_data():
con1=[Link]
(host='localhost',user='root',password="",database='test',charset
='utf8') mycursor= ________________ #statement1
rno= int(input("Enter the Roll Number::"))
name=input("Enter the name::")
Class=int(input("Enter the class::"))
marks=int(input("Enter the marks::"))
30
[Link]("create table Ayush (rno integer ,name
char(10),Class integer,marks integer)")
[Link]=( "insert into student
values({},'{}',{},{}).format(rno,name,Class,marks)")
_______________ #statement2
___________________#statement3
print("Data Added successfully")
Ans.
Output:
Q5. Write a menu driven program using python interface with mysql to
make various functions in student data.
Ans.
while True:
import [Link] as sqltor
31
con1= [Link](host= "localhost", user= "root", password = "",
database= "test",charset= "utf8")
a=int(input(''' ------------------------------------------------------------------- ------------
DELHI JAIN PUBLIC SCHOOL
------------------------------------------------------------------------------- - What
Do You want to do?
- [Link] New Student Data
- [Link] Existing Student Data
- [Link] Existing Student Data
- [Link] Particular Student Data
- [Link] All Student Data
-------------------------------------------------------------------------------
:'''))
if a== 1:
b1= int(input("How many students:"))
for i in range (b1):
mycursor= [Link]()
AdmNo= int(input("Enter your admission no."))
Name = input("Enter your name")
DOB = input("Enter your date of birth in alphanumeric form ")
Fees= float(input("Enter your fees"))
query= ("insert into Students values({}, '{}', '{}', {})".format(AdmNo,
Name, DOB, Fees))
[Link](query)
[Link]()
print("Data Added Successfully")
elif a==2:
32
mycursor= [Link]()
b2= int(input('''What do you want to change?
[Link]
[Link]
[Link]'''))
AdmNo= int(input("Enter your admission no."))
if b2==1:
c2=input("Enter the new Name")
[Link]("update Students set Name ='{}' where
AdmNo={}".format(c2, AdmNo))
[Link]()
print("Data Added Successfully")
elif b2==2:
c2=input("Enter the DOB in alphanumeric form")
[Link]("update Students set DOB ='{}' where
AdmNo={}".format(c2, AdmNo))
[Link]()
print("Data Added Successfully")
elif b2==3:
c2=input("Enter the new Fee")
[Link]("update Students set Fees ={} where
AdmNo={}".format(c2, AdmNo))
[Link]()
print("Data Added Successfully")
elif a==3:
mycursor= [Link]()
AdmNo= int(input("Enter admission no. of student whose data you want to
delete"))
[Link]("delete from Students where
AdmNo={}".format(AdmNo))
33
[Link]()
print("Data of the following student is deleted successfully")
[Link]("select Name, Admno, DOB, Fees from students where
AdmNo={}".format(AdmNo))
p=[Link]()
for i in p:
print (i)
elif a==4:
mycursor= [Link]()
AdmNo= int(input("Enter admission no. of student whose data you want to
View"))
[Link]("select Name, Admno, DOB, Fees from students where
AdmNo={}".format(AdmNo))
p=[Link]()
[Link]()
for i in p:
print (i)
elif a==5:
mycursor= [Link]()
[Link]("select * from students")
p=[Link]()
for i in p:
print (i)
b=input("Yes,No")
if b== 'no':
break
34
Output: Choice “1”
Choice “2”
35
Choice “3”
36
Choice “4”
Choice “5”
37
38