You are on page 1of 46

Computer

Science
Report File

By : Dhruv Jain

XII-B
Board Roll No:

1
Index
Python Programs
S. No. Program Page Signature
No. and Remarks
1. Write a function that receives two string arguments and 5
checks whether they are of same length (returns True else
False).
2. WAP that creates a list of all integers less than 100 that are 6
multiples of 3 & 5.
3. WAP that calculates and prints the number of seconds in a 7
year.
4. Read a text file line by line and display each word separated 8
by a #.
5. Read a text file and display the number of vowels/ 9
consonants/uppercase/lowercase characters in the file.
6. Remove all the lines that contain the character 'a' in a file 10
and write it to another file.
7. Create a binary file with name and roll number. Search for a 11
given roll number and display the name, if not found display
appropriate message.
8. Create a binary file with roll number, name, and marks. Input 12
a roll number and update the marks.
9. Write a random number generator that generates random 14
numbers between 1 and 6 (simulates a dice).
10. Create a CSV file by entering user-id and password, read and 15
search the password for given user-id.
11. Write a program to know the cursor position and print the 17
text according to the below given specifications:
o Print the initial position
o Move the cursor to 4th position
o Display next 5 characters
o Move the cursor to the next 10 characters
o Print the current cursor position
o Print next 10 characters from the current cursor position

2
12. Write a program to store customer data into a binary file 18
cust.dat using a dictionary and print them on screen after
reading them. The customer data contains ID as key, and
name, city as values.
13. Write a program to create a binary file sales.dat and write a 19
menu driven program to do the following:
a. Insert record
b. Search Record
c. Update Record
d. Display record
e. Exit
14. Read a CSV file top5.csv and print the contents in a proper 23
format. The data for top5.csv file are as following:

15. Write a menu-driven python program to implement all stack 24


operations.

MySQL Operations
S. No. Operations Page Signature
No. and Remarks
1. Set-1 27

2. Set-2 29

3. Set-3 31

4. Set-4 33

5. Set-5 35

3
Python-MySQL Connectivity
S. No. Python-MySQL Interface Programs Page Signature
No. and Remarks
1. Write a MySQL connectivity program in Python to 37
o Create a database school
o Create a table students with the specifications – ROLLNO
integer, STNAME character(10) in MySQL and perform the
following operations:
▪ Insert two records in it
▪ Display the contents of the table
2. Write a menu-driven program to store data into a MySQL 38
database named shop and table customer as following:
1. Add customer details
2. Update customer details
3. Delete customer details
4. Display all customer details
3. Modify the above program and display the customer details 43
based on the following menu:
1. Display customer details by city
2. Display customer details by bill amount
3. Display customer details by name
4. Display customer details by category

4
Python Programs
Question 1: Write a function that receives two string arguments and
checks whether they are of same length(returns True else False).

def len_check(str1,str2):
if len(str1)==len(str2):
return True
else:
return False
str1=input("Enter the first string:")
str2=input("Enter the second string:")
print(len_check(str1,str2))

5
Question 2: WAP that creates a list of all integers less than 100 that are
multiples of 3 & 5.

list1=[]
for i in range(1,101):
if i%3==0 and i%5==0:
list1+=[i]
print(list1)

6
Question 3: WAP that calculates and prints the number of seconds in a
year.

choice=input("Is it a leap year?(y/n):")


if choice=="y":
print(366*24*60*60,"seconds in a leap year")
elif choice=="n":
print(365*24*60*60,"seconds in a non leap year")
else:
print("Invalid choice!")

7
Question 4: Read a text file line by line and display each word separated
by a #.

f=open("text.txt","r")
print("text.txt:",f.read(),sep="\n")
f=open("text.txt","r")
for line in f:
for word in line.strip():
print(word,end="#")
print()

8
Question 5: Read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file.

f=open("text.txt","r")
print("text.txt:",f.read(),sep="\n")
f=open("text.txt","r")
vowel,cons,upper,lower=0,0,0,0
for i in f.read():
if i.isalpha():
if i in ['a','e','i','o','u','A','E','I','O','U']:
vowel+=1
else:
cons+=1
if i.isupper():
upper+=1
else:
lower+=1 print("Vowels:",vowel,"\nConsonants:",cons,"\nUppercase:",upper,"\
nLowercase:",lower)

9
Question 6: Remove all the lines that contain the character 'a' in a file
and write it to another file.

f=open('text.txt','r')
print("text.txt before:",f.read(),sep="\n")
f=open("text.txt","r")
list1=[]
list2=[]
for line in f.readlines():
if 'a' in line:
list1+=[line]
else:
list2+=[line]
f=open('text.txt','w')
f.writelines(list2)
g=open('atext.txt','w')
g.writelines(list1)
g=open("atext.txt","r")
print("atext.txt:",g.read(),sep="\n")
f=open("text.txt","r")
print("text.txt after:",f.read(),sep="\n")

10
Question 7: Create a binary file with name and roll number. Search for a
given roll number and display the name, if not found display appropriate
message.

import pickle
f=open('btext.dat','wb')
n=int(input("Enter the number of students:"))
dict1={}
for i in range(n):
roll=int(input("Enter the roll number:"))
name=input("Enter the name:")
dict1[roll]=name
pickle.dump(dict1,f)
f=open('btext.dat','rb')
data=pickle.load(f)
print("btext.dat:",data,sep="\n")
num=int(input("Enter the roll number to be searched:"))
if num in data:
print("Name associated with roll number",num,"is",data[num])
else:
print("Roll Number not found!")

11
Question 8: Create a binary file with roll number, name, and marks. Input
a roll number and update the marks.

import pickle
f=open('btext.dat','wb')
n=int(input("Enter the number of students:"))
dict1={}
for i in range(n):
roll=int(input("Enter the roll number:"))
name=input("Enter the name:")
marks=int(input("Enter the marks:"))
dict1[roll]=[name,marks]
pickle.dump(dict1,f)
f=open('btext.dat','rb')
data=pickle.load(f)
print("btext.dat before:",data,sep="\n")
num=int(input("Enter the roll number of the student whose marks are to be updated:"))
if num in data:
new_marks=int(input("Enter the new marks:"))
data[num][1]=new_marks
f=open('btext.dat','wb')
pickle.dump(data,f)
f=open('btext.dat','rb')
print("btext.dat after:",pickle.load(f),sep="\n")
else:
print("Roll Number not found!")

12
13
Question 9: Write a random number generator that generates random
numbers between 1 and 6 (simulates a dice).

import random
dice=random.randint(1,6)
print("Random Number Generated:",dice)

14
Question 10: Create a CSV file by entering user-id and password, read
and search the password for given user-id.

import csv
f=open("passwords.csv","w",newline="")
g=csv.writer(f)
n=int(input("Enter the number of IDs:"))
for i in range(n):
user=input("Enter the user-id:")
password=input("Enter the password:")
g.writerow([user,password])
f.close()
f=open("passwords.csv","r")
h=csv.reader(f)
print("passwords.csv:")
for j in h:
print(j)
f.close()
f=open("passwords.csv","r")
h=csv.reader(f)
id=input("Enter the user-id to be searched:")
found=False
for k in h:
if k[0]==id:
print("Password associated with user-id",id,"is",k[1])
found=True
if found==False:
print("User-id not found!")

15
16
Question 11: Write a program to know the cursor position and print the
text according to the below given specifications:
o Print the initial position
o Move the cursor to 4th position
o Display next 5 characters
o Move the cursor to the next 10 characters
o Print the current cursor position
o Print next 10 characters from the current cursor position

f=open("para.txt")
print("para.txt:")
print(f.read())
f.seek(0)
print("Initial Position:",f.tell())
f.seek(4)
print("Next 5 characters:",f.read(5))
f.seek(19)
print("Current Position:",f.tell())
print("Next 10 characters:",f.read(10))

17
Question 12: Write a program to store customer data into a binary file
cust.dat using a dictionary and print them on screen after reading them.
The customer data contains ID as key, and name, city as values.

import pickle
f=open("cust.dat","wb")
n=int(input("Enter the number of entries:"))
for i in range(n):
d={}
id=input("Enter the customer ID:")
name=input("Enter the customer name:")
city=input("Enter the city:")
d[id]=[name,city]
pickle.dump(d,f)
f=open("cust.dat","rb")
try:
print("Customer Data")
while True:
print(pickle.load(f))
except:
pass

18
Question 13: Write a program to create a binary file sales.dat and write a
menu driven program to do the following:
a. Insert record
b. Search Record
c. Update Record
d. Display record
e. Exit

import pickle
while True:
print("~~~MENU~~~")
print("1. Insert Record")
print("2. Search Record")
print("3. Update Record")
print("4. Display Record")
print("5. Exit")
c=int(input("Enter the choice:"))
if c==1:
f=open("sales.dat","ab")
id=input("Enter the product ID:")
name=input("Enter the product name:")
price=int(input("Enter the product price:"))
qty=int(input("Enter the product quantity:"))
pickle.dump([id,name,price,qty],f)
elif c==2:
f=open("sales.dat","rb")
id=input("Enter the id of the product to be searched:")
try:

19
while True:
r=pickle.load(f)
if r[0]==id:
print(["ID", "Name", "Price", "Quantity"])
print(r)
break
except:
print("Record Not Found!")
elif c==3:
f = open("sales.dat", "rb")
id = input("Enter the id of the product to be updated:")
l=[]
try:
while True:
r=pickle.load(f)
if r[0]==id:
name = input("Enter the new product name:")
price = int(input("Enter the new product price:"))
qty = int(input("Enter the new product quantity:"))
r=[id,name,price,qty]
l+=[r]
except:
pass
f=open("sales.dat","wb")
for i in l:
pickle.dump(i,f)
elif c==4:
f=open("sales.dat","rb")
print(["ID","Name","Price","Quantity"])
try:

20
while True:
print(pickle.load(f))
except:
pass
elif c==5:
exit()
else:
print("Enter a valid choice!")

21
22
Question 14: Read a CSV file top5.csv and print the contents in a proper
format. The data for top5.csv file are as following:

import csv
f=open("top5.csv","r")
g=csv.reader(f)
for i in g:
print(i)

23
Question 15: Write a menu-driven python program to implement all
stack operations.

def isEmpty(stack):
if stack==[]:
return True
else:
return False
def Push(stack,item):
stack.append(item)
def Pop(stack):
if isEmpty(stack):
print("Stack Underflow!")
else:
return stack.pop()
def Peek(stack):
if isEmpty(stack):
print("Stack Empty!")
else:
print(stack[-1])
def Display(stack):
if isEmpty(stack):
print("Stack Empty!")
else:
print("Stack:")
for i in range(len(stack)-1,-1,-1):
print(stack[i])
stack=[]
while True:

24
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")
c=int(input("Enter the choice:"))
if c==1:
item=input("Enter the item to push:")
Push(stack,item)
elif c==2:
print("Popped Item:",Pop(stack))
elif c==3:
Peek(stack)
elif c==4:
Display(stack)
elif c==5:
exit()
else:
print("Enter a valid choice!")

25
26
MySQL Operations
Set-1: Consider the following MOVIE table and write the SQL queries
based on it.

a. Display all information from movie.


b. Display the type of movies.
c. Display movieid, moviename, total_earning by showing the business
done by the movies. Calculate the business done by movie using the sum
of productioncost and businesscost.
d. Display movieid, moviename and productioncost for all movies with
productioncost greater than 150000 and less than 1000000.
e. Display the movie of type action and romance.

a) Select * from MOVIE;

27
b) Select DISTINCT Type from MOVIE;

c) Select Movie_ID,MovieName,ProductionCost+BusinessCost AS Total_Earning from MOVIE;

d) Select Movie_ID,MovieName,ProductionCost from MOVIE where ProductionCost>150000 AND


ProductionCost<1000000;

e) Select MovieName from MOVIE where Type in ('Action','Romance');

28
Set-2: Consider the given table patient and write following queries:

1. Display the total charges of patients admitted in the month of


November.
2. Display the eldest patient with name and age.
3. Count the unique departments.
4. Display average charges.

1. Select sum(charges) from patient where dateofadm like "%11 ";

2. select pname,age from patient where age=(select max(age) from patient);

29
3. Select count(DISTINCT department) from patient;

4. Select avg(charges) from patient;

30
Set-3: 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 with team names –
Tehlka, Toofan, Aandhi and Shailab. 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:
o It should have a column TeamID for storing an integer value
between 1 to 9, which refers to unique identification of a team.
o Each TeamID should have its associated name (TeamName),
which should be a string of length less than 10 characters. (4 team
names given above)
o Using table level constraint, make TeamID as the primary key.
c. Show the structure of the table TEAM using a SQL statement.
d. As per the preferences of the students four teams were formed as
given below. Insert these four rows in TEAM table:
o Row 1: (1, Tehlka)
o Row 2: (2, Toofan)
o Row 3: (3, Aandhi)
o Row 3: (4, Shailab)
o Show the contents of the table TEAM using a DML statement.

a) Create database Sports;

31
b) Create table TEAM(TeamID int check(TeamID between 1 and 9),TeamName
varchar(10) check(length(TeamName)<10), primary key(TeamID));

c) Desc TEAM;

d) Insert into TEAM values(1,'Tehlka');


Insert into TEAM values(2,'Toofan');
Insert into TEAM values(3,'Aandhi');
Insert into TEAM values(4,'Shailab');
Select * from TEAM;

32
Set-4: Now create another table MATCH_DETAILS and insert data as
shown below. Choose appropriate data types and constraints for each
attribute.

Display the matchid, teamid, teamscore(both team score) who scored


more than 70 in the firstinning(means M1) along with team name.
Display matchid, secondTeamID and secondTeamScore between 100 to
160.
Display all details whose MatchDate is 23rd December of the year 2021.

create table MATCH_DETAILS(MatchID VARCHAR(3) PRIMARY KEY, MatchDate DATE,FirstTeamID


INT,SecondTeamID INT,FirstTeamScore INT,SecondTeamScore INT);
insert into MATCH_DETAILS VALUES('M1','2021-12-20',1,2,107,93);
insert into MATCH_DETAILS VALUES('M2','2021-12-21',3,4,156,158);
insert into MATCH_DETAILS VALUES('M3','2021-12-22',1,3,86,81);
insert into MATCH_DETAILS VALUES('M4','2021-12-23',2,4,65,67);
insert into MATCH_DETAILS VALUES('M5','2021-12-24',1,4,52,88);
insert into MATCH_DETAILS VALUES('M6','2021-12-25',2,3,97,68);
SELECT * FROM MATCH_DETAILS;

33
select MatchID, FirstTeamID,SecondTeamID,FirstTeamScore,SecondTeamScore, TeamName from
MATCH_DETAILS M, TEAM T where (T.TeamID in (FirstTeamID,SecondTeamID)) AND (MatchID='M1') AND
(FirstTeamScore>70 AND SecondTeamScore>70);

select MatchID,SecondTeamID,SecondTeamScore from MATCH_DETAILS where SecondTeamScore between


100 and 160;

select * from MATCH_DETAILS where MatchDate='2021-12-23';

34
Set-5: Consider the stock table to answer the below queries.

a. Display all the items in the ascending order of stockdate.


b. Display maximum price of items for each dealer individually as per
dcode from stock.
c. Display all the items in descending orders of item names.
d. Display average price of items for each dealer individually as per dcode
from stock which average price is more than 5.
e. Display the sum of quantity for each dcode.

a) select * from stock order by stockdate;

35
b) select dcode,max(unitprice) from stock group by dcode;

c) select * from stock order by item desc;

d) select dcode,avg(unitprice) from stock group by dcode having avg(unitprice)>5;

e) select dcode,sum(qty) from stock group by dcode;

36
Python-MySQL Interface Programs
Question 1: Write a MySQL connectivity program in Python to
o Create a database school
o Create a table students with the specifications – ROLLNO integer,
STNAME character(10) in MySQL and perform the following operations:
▪ Insert two records in it
▪ Display the contents of the table

import mysql.connector as sql


con=sql.connect(host="localhost",user="root",passwd="22python44")
cur=con.cursor()
cur.execute("create database school")
cur.execute("use school")
cur.execute("create table students(ROLLNO INT, STNAME CHAR(10))")
con.commit()
print("Database school and table students created")
print("Inserting two records")
for i in range(2):
rollno=int(input("Enter the roll number:"))
stname=input("Enter the student name:")
cur.execute("insert into students values({},'{}')".format(rollno,stname))
con.commit()
print("Displaying the table")
cur.execute("select * from students")
print(('ROLLNO','STNAME'))
for i in cur.fetchall():
print(i)

37
Question 2: Write a menu-driven program to store data into a MySQL
database named shop and table customer as following:
1. Add customer details
2. Update customer details
3. Delete customer details
4. Display all customer details

import mysql.connector as sql


con=sql.connect(host="localhost",user="root",passwd="22python44")
cur=con.cursor()
cur.execute("create database shop")
cur.execute("use shop")
cur.execute("create table customer(CID int,CName varchar(20),City varchar(10),Category
varchar(10),Bill_Amount float)")
con.commit()
while True:
print("1. Add customer details")
print("2. Update customer details")
print("3. Delete customer details")
print("4. Display all customer details")
print("5. Exit")
c=int(input("Enter the choice:"))
if c==1:
cid=int(input("Enter the customer ID:"))
cname=input("Enter the customer name:")
city=input("Enter the city:")
cat=input("Enter the category:")
amt=float(input("Enter the bill amount:"))

38
cur.execute("insert into customer values({},'{}','{}','{}',{})".format(cid,cname,city,cat,amt))
con.commit()
print("Customer Details Added!")
elif c==2:
cid=int(input("Enter the customer ID to update the details of:"))
cur.execute("select * from customer where CID={}".format(cid))
print("Current Details")
print(("CID","CName","City","Category","Bill_Amount"))
print(cur.fetchone())

cname=input("Enter the new customer name:")


city=input("Enter the new city:")
cat=input("Enter the new category:")
amt=float(input("Enter the new bill amount:"))
cur.execute("update customer set CName='{}',City='{}',Category='{}',Bill_Amount={} where
CID={}".format(cname,city,cat,amt,cid))
con.commit()
print("Customer Details Updated!")
elif c==3:
cid=int(input("Enter the customer ID to delete the details
of:")) cur.execute("delete from customer where
CID={}".format(cid)) con.commit()
print("Customer Record Deleted!")
elif c==4:
cur.execute("select * from customer")
print("All Customer Details")
print(("CID","CName","City","Category","Bill_Amount"))
for i in cur.fetchall():
print(i)
elif c==5:
exit()

39
else:
print("Enter a valid choice!")

40
41
42
Question 3: Modify the above program and display the customer details
based on the following menu:
1. Display customer details by city
2. Display customer details by bill amount
3. Display customer details by name
4. Display customer details by category

import mysql.connector as sql


con=sql.connect(host="localhost",user="root",passwd="22python44",database="shop")
cur=con.cursor()
cur.execute("select * from customer")
print("All Details in Customer Table")
for i in cur.fetchall():
print(i)
while True:
print("1. Display customer details by city")
print("2. Display customer details by bill amount")
print("3. Display customer details by name")
print("4. Display customer details by category")
print("5. Exit")
c=int(input("Enter the choice:"))
if c==1:
city=input("Enter the city to display the customer details of:")
cur.execute("select * from customer where City='{}'".format(city))
r=cur.fetchall()
if len(r)==0:
print("No Records!")
continue

43
print("Details by City")
print(("CID", "CName", "City", "Category", "Bill_Amount"))
for i in r:
print(i)
elif c==2:
amt=float(input("Enter the bill amount to display the customer details of:"))
cur.execute("select * from customer where Bill_Amount={}".format(amt))
r = cur.fetchall()
if len(r) == 0:
print("No Records!")
continue
print("Details by Bill Amount")
print(("CID", "CName", "City", "Category", "Bill_Amount"))
for i in r:
print(i)
elif c==3:
cname=input("Enter the name to display the customer details of:")
cur.execute("select * from customer where CName='{}'".format(cname))
r = cur.fetchall()
if len(r) == 0:
print("No Records!")
continue
print("Details by Name")
print(("CID", "CName", "City", "Category", "Bill_Amount"))
for i in r:
print(i)
elif c==4:
cat=input("Enter the category to display the customer details of:")
cur.execute("select * from customer where Category='{}'".format(cat))
r = cur.fetchall()

44
if len(r) == 0:
print("No Records!")
continue
print("Details by Category")
print(("CID", "CName", "City", "Category", "Bill_Amount"))
for i in r:
print(i)
elif c==5:
exit()
else:
print("Enter a valid choice!")

45
46

You might also like