0% found this document useful (0 votes)
5 views

CS Practical File

The document is a practical file for a Computer Science course by Ojas Srivastava, detailing various programming tasks and solutions using Python. It includes code snippets for file operations, data manipulation, and data analysis using libraries like pickle and csv. The tasks cover reading from and writing to files, counting characters, and filtering data based on specific criteria.

Uploaded by

ojas srivastava
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

CS Practical File

The document is a practical file for a Computer Science course by Ojas Srivastava, detailing various programming tasks and solutions using Python. It includes code snippets for file operations, data manipulation, and data analysis using libraries like pickle and csv. The tasks cover reading from and writing to files, counting characters, and filtering data based on specific criteria.

Uploaded by

ojas srivastava
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Ojas Srivastava 12th - Aryabhatta 2024-25

COMPUTER SCIENCE
PRACTICAL FILE

Ojas Srivastava
12th Aryabhatta
Q1. Print lines with one or more ‘a’
Ojas Srivastava 12th - Aryabhatta 2024-25

x = input('name of file to read ')


with open(f'{x}.txt','r') as f:
read = f.readlines()
for line in read:
if line.count('a') >= 1:
print(line)

Q2. Print length of longest line in a file

x = input('name of file to read ')


with open(f'{x}.txt','r') as f:
read = f.readlines()
lines = list(read)
lengths = []
for i in lines:
lengths.append(len(i))
print(max(lengths))

Q3. Print number of lines starting with ‘A’

with open("zig zag.txt", "r") as f:


read =f .readlines()
print(list(read))
count = 0
for i in read:
if i[0] == "A":
count += 1
print(count)
Ojas Srivastava 12th - Aryabhatta 2024-25

Q4. Count Uppercase and lowercase letters in a file

with open("zig zag.txt","r") as f:


read = f.read()
print(read)
u_count=0
l_count=0
for char in read:
if char.isalpha():
if char.isupper():
u_count+=1
else:
l_count+=1
print(f"Uppercase Letters: ", u_count)
print(f"Lowercase Letters: ", l_count)

Q5.
with open("zig zag.txt","r") as f:
read = f.read()
str = ""
for char in read:
if char in [".","?","!"]:
str += char
print(str)
Ojas Srivastava 12th - Aryabhatta 2024-25

str = ""
else:
str += char

Q6. Print line if it starts with an uppercase letter

with open("zig zag.txt", "r") as f:


read=f.readlines()
print(list(read))
for i in read:
if i[0].isupper():
print(i.rstrip("\n"))

Q7. Read and write in the same file

with open('zig zag.txt','a+') as f:


read = f.read()
f.write(f'{read}\nsaunf')
f.close()
with open('zig zag.txt','r') as f:
print("The new text in the file is:"+f"{f.read()}")
Ojas Srivastava 12th - Aryabhatta 2024-25

Q8. Read and print line number and line from a text

with open('zig zag.txt','r') as f:


read = f.readlines()
read = list(read)
line = 0
for i in read:
line += 1
print(line,i.rstrip('\n'))

Q9. Read a file and write lines with only uppercase in another file

with open('zig zag.txt','r') as f:


with open('zig zag2.txt','w') as f2:
read = f.readlines()
for i in read:
if i.isupper():
f2.write(i)
read = list(read)
Ojas Srivastava 12th - Aryabhatta 2024-25

print(read)
f2.close()
f.close()
with open('zig zag2.txt','r') as f2:
read = f2.readlines()
print(f"Output is {list(read)}")

Q10. Search name and address of people who are more than 30 years old

with open("zig zag.txt", "r") as f:


both = f.readlines()
data = []
for i in both:
split = i.split(" ")
data.append(split)
for i in data:
if int(i[-1]) > 30:
print(f"{i[0]}, {i[1]}")
f.close()

Q11. Sort text into uppercase, lowercase and other

with open('zig zag.txt','r') as f:


read = f.readlines()
letters = []
uppercase = []
lowercase = []
numbers = []
symbols = []
for line in read:
Ojas Srivastava 12th - Aryabhatta 2024-25

line = list(line)
for char in line:
if char.isupper() == True:
uppercase.append(char)
if char.islower() == True:
lowercase.append(char)
if char.isdigit() == True:
numbers.append(char)
if char.isalnum() == False:
symbols.append(char)
upper = ''
lower = ''
number = ''
symbol = ''
for i in range(len(uppercase)):
upper += uppercase[i]
for j in range(len(lowercase)):
lower += lowercase[j]
for k in range(len(numbers)):
number += numbers[k]
for l in range(len(symbols)):
symbol += symbols[l]
with open('uppercase.txt','w') as f2:
f2.write(upper)
f2.close()
with open('lowercase.txt','w') as f3:
f3.write(lower)
f3.close()
with open('numbers.txt','w') as f4:
f4.write(number)
f4.close()
with open('symbols.txt','w') as f5:
f5.write(symbol)
f5.close()
f.close()

Input

Output
Ojas Srivastava 12th - Aryabhatta 2024-25

Q12. Count number of names starting with S

import pickle
import random
names = ['Beyonce','Kanye','Adele']
with open('zig zag4.dat','wb') as f:
n = []
x = len(names)
for i in range(20):
y = random.randrange(x)
n.append(names[y])
pickle.dump(n,f)
f.close()
count = 0
with open('zig zag4.dat','rb') as f:
read = pickle.load(f)
print(read)
for name in read:
if name[0] == 'S':
count += 1
print(count)

Q13. Sequence of numbers


Ojas Srivastava 12th - Aryabhatta 2024-25

import pickle
with open('numbers.dat','wb') as f:
for i in range(10):
a = [f for f in range(i)]
pickle.dump(a,f)
f.close()
with open('numbers.dat','rb') as f:
try:
while True:
print(pickle.load(f))
except:
f.close()

Q.14. Update an employees’s data

import pickle
import random
salaries = [1,100,20000,2430000,500000000]
with open("record.dat", "wb") as f:
for employee in "abcdefghij":
data = [employee,salaries[random.randrange(len(salaries))]]
pickle.dump(data,f)
f.close()
def update(name,salary):
flag = False
with open("temp.dat","wb") as f:
Ojas Srivastava 12th - Aryabhatta 2024-25

with open("record.dat", "rb") as a:


try:
while True:
read = pickle.load(a)
if read[0] == name:
pickle.dump([name,salary],f)
flag = True
print("Updated Data")
else:
pickle.dump(read,f)
except:
if flag != True:
print("Employee not Found")
update("a",23425)

Q15. Search for all patients with a particular disease

import pickle
import random
diseases=["Covid-19","Cholera","Typhoid"]
with open("PATIENTS.dat", "wb") as f:
id_=1
for i in "abcdefghijklmnop":
random_disease=random.randrange(0,3)
patient=[id_,i,diseases[random_disease]]
pickle.dump(patient,f)
id_+=1
f.close()
def countrec(disease):
with open("PATIENTS.dat", "rb") as f:
try:
Ojas Srivastava 12th - Aryabhatta 2024-25

while True:
read=pickle.load(f)
if read[2]==disease:
print(read)
except:
pass
countrec("Covid-19")

Q16. Add plants to database and print plants with price > 500

import pickle
import random
prices = [11,51,101,501,1001,2001]
plants = ['rose','bonsai','tulip']
with open('nursery.dat','wb+') as f:
for i in range(20):

pickle.dump([plants[random.randrange(len(plants))],prices[random.randrang
e(len(prices))]],f)
f.close()
with open('nursery.dat','rb') as f:
try:
while True:
read = pickle.load(f)
if read[1] > 500:
print(read)
except:
pass
f.close()
Ojas Srivastava 12th - Aryabhatta 2024-25

Q17. Print data of students whose score is more than 75

import pickle
import random
marks = [60,70,80,90,100]
students = ['Ojas','Ishan','Tanishq']
with open('report.dat','wb') as f:
for y in students:
pickle.dump([y,marks[random.randrange(len(marks))]],f)
f.close()
with open('report.dat','rb') as f:
try:
while True:
read = pickle.load(f)
if read[1] > 75:
print(read)
except:
pass
f.close()

Q18. Read sports data from a file and write all athletics data in another file

import pickle
import random
places = ['delhi','noida','gurugram']
dates = ['23rd','24th','25th']
sports = ['athletics','tennis','soccer','cricket','golf']
with open('report.dat','wb') as f:
for y in sports:
Ojas Srivastava 12th - Aryabhatta 2024-25

pickle.dump([y,dates[random.randrange(len(dates))],places[random.randran
ge(len(places))]],f)
f.close()
with open('report.dat','rb') as f:
try:
while True:
read = pickle.load(f)
if read[0] == 'athletics':
print(read)
except:
pass
f.close()

Q19. Search file for a player, players of a country, and add a player’s data

def player_search():
with open("PLAYERS.dat", "rb") as f:
try:
while True:
read=pickle.load(f)
if read[1]=="a":
print(read, "\n")
except:
pass
def country_search(country):
with open("PLAYERS.dat", "rb") as f:
count=0
try:
while True:
read=pickle.load(f)
if read[2]==country:
count+=1
print(read)
except:
print(count, "Players\n")
def add():
with open("PLAYERS.dat", "ab") as f:
data=eval(input("Enter a players data [id,name,country]\n"))
pickle.dump(data,f)
Ojas Srivastava 12th - Aryabhatta 2024-25

print("Updated Successfully")
player_search()
country_search("India")
add()

Q20. Input data into store inventory

import pickle
import random
countries=["India","Australia","Sweden","Sri Lanka"]
with open("PLAYERS.dat", "wb") as f:
id_=1
for i in "abcdefghijklmnop":
country=random.randrange(0,len(countries))
player=[id_,i,countries[country]]
pickle.dump(player,f)
id_+=1
f.close()
import pickle
n=int(input("Enter number of inputs\n"))
with open("Records.dat","wb") as f:
for ch in range(n):
data=eval(input("Enter the data[ItemNo,ItemName,Qty,Price]\n"))
pickle.dump(data,f)
f.close()
with open("Records.dat","rb") as f:
try:
while True:
read=pickle.load(f)
print(read)
except:
f.close()
Ojas Srivastava 12th - Aryabhatta 2024-25

Q21. Print students in need of remedial classes from file (Marks <40)

import random as r
import pickle as p
marks=[20,25,30,40,60,90]
with open("Student.dat", "wb+") as f:
for student in ("abcdefg"):
mark=r.randrange(0,len(marks))
p.dump([student, marks[mark]],f)
f.flush()
f.seek(0)
try:
while True:
x=p.load(f)
if x[1]<=40:
print(x)
except:
f.close()

Q22. Write data of all basketball players in a different file


import pickle
import random
games=["Basket Ball","Football","Cricket"]
with open("game.dat","wb") as f:
for player in "abcdefghijklmnop":
data=[player,games[random.randrange(len(games))]]
pickle.dump(data,f)
f.close()
with open("basketball.dat","wb") as f:
with open("game.dat","rb") as a:
Ojas Srivastava 12th - Aryabhatta 2024-25

try:
while True:
read=pickle.load(a)
if read[1]=="Basket Ball":
pickle.dump(read,f)
print(read)
except:
a.close()
f.close()

Q23. Edit a product’s stock in database

import pickle
with open("PRODUCT.dat", "wb") as f:
a=[{"prod_code":"4543","prod_desc":"For 2 year olds","stock":3},
{"prod_code":"3423","prod_desc":"For 7 year olds","stock":43},
{"prod_code":"2212","prod_desc":"For 9 year olds","stock":54}]
for i in a:
pickle.dump(i,f)
f.close()
def edit(code,stock):
with open("PRODUCT.dat", "rb") as f:
data=[]
try:
while True:
x=pickle.load(f)
data.append(x)
except:
f.close()
try:
with open("PRODUCT.dat", "wb") as f:
Ojas Srivastava 12th - Aryabhatta 2024-25

for i in data:
if i["prod_code"]==code:
u={"prod_code":code,"prod_desc":i["prod_desc"],"stock":stock}
pickle.dump(u,f)
print(f"Updated {code} stock ",u)
else:
pickle.dump(i,f)
f.close()
except:
print("Invalid Product Code")
edit("3423",5)

Q24. Read student data from a file and sum up their marks and write the
data in a new file

import csv
with open("result.csv","r",newline="") as f:
cr=csv.reader(f)
next(cr)
data=[]
for i in cr:
l=[i[0],i[1],int(i[2])+int(i[3])+int(i[4])]
data.append(l)
f.close()
with open("copy.csv","w",newline="") as f:
cw=csv.writer(f)
cw.writerows(data)
print("Copying of data complete")

INPUT

OUTPUT
Ojas Srivastava 12th - Aryabhatta 2024-25

Q25. Read data of products from file and add up the total cost

import csv
with open("zig zag.csv", "r", newline="") as f:
cr=csv.reader(f)
total=0
for i in cr:
total+=int(i[1])*int(i[2])
print("The total cost is",total)

Q26. Print data of country if the capital is more than 5 letters long

import csv
with open("result.csv","r",newline="") as f:
cr=csv.reader(f)
for i in cr:
if len(i[1])>=6:
print(i)

Q27. Add device and/or print number of devices costing <1000

import csv
def Add_Device():
with open("Peripheral.csv", "w", newline="") as f:
cr=csv.writer(f)
data=eval(input("Enter device data [ID,Name,Price] or '$' to quit\n"))
if data=="$":
Ojas Srivastava 12th - Aryabhatta 2024-25

return
cr.writerow(data)
f.close()
def Count_Device():
with open("Peripheral.csv", "r", newline="") as f:
cr=csv.reader(f)
count=0
for line in cr:
if int(line[2])<1000:
count+=1
print(f"{count} devices costing less than 1000")
f.close()
Add_Device()
Count_Device()

Q28. Accept grocery data from user and write in file

import csv
with open("Groceries.csv","w",encoding="utf8") as f:
cw=csv.writer(f)
while True:
_input=eval(input("Enter data for an item[code,name,qty,price] or $ to
exit\n"))
if _input=="$":
break
cw.writerow(_input)
print("Added data to file")

Q29. Write student info to file


Ojas Srivastava 12th - Aryabhatta 2024-25

import csv
with open("one.csv", "w",newline="") as f:
cw=csv.writer(f)
cw.writerow(["Roll.No","Name","Marks"])
while True:
data=eval(input("Input data [Roll.No,Name,Marks] or $ to exit\n"))
if data=="$":
break
cw.writerow(data)
print("Updated File")
f.close()

Q30. Read csv file and print the data in each rows and the number of
elements

import csv
with open("one.csv", "r", encoding="utf8",newline="") as f:
cr=csv.reader(f)
count=0
for i in cr:
count+=1
if i[2].isdigit():
if int(i[2])>=80:
print(i)
print(f"{count-1} elements")

Q31. WAP to create a stack for storing only odd numbers out of the inputs.
WAP to display the largest odd number in the stack

def add():
for i in range(5):
x = int(input('enter a number: '))
if x%2 == 1:
Ojas Srivastava 12th - Aryabhatta 2024-25

stack.append(x)
else:
continue
menu()
def delete_for_max():
h = [0]
for i in range(len(stack)):
x = stack.pop()
if x > h[-1]:
h.append(x)
else:
continue
print(h[-1])
def menu():
add_delete = input('add or find? ').lower()
if add_delete == 'add':
add()
if add_delete == 'find':
delete_for_max()
stack = []
menu()

Q32 -
Ojas Srivastava 12th - Aryabhatta 2024-25

Code –
import mysql.connector

# Connect to MySQL server


connection =
mysql.connector.connect(host="localhost",user="root",password="1234")

cursor = connection.cursor()

# Create the database


cursor.execute("CREATE DATABASE IF NOT EXISTS LOANS_DB")
cursor.execute("USE LOANS_DB")

# Create the LOANS table


cursor.execute('''
CREATE TABLE IF NOT EXISTS LOANS (
AccNo INT PRIMARY KEY,
Cust_Name VARCHAR(50),
Loan_Amount INT,
Installments INT,
Int_Rate FLOAT,
Start_Date DATE,
Interest INT
)
''')

# Insert the data into the LOANS table


loans_data = [
(1, 'R.K. Gupta', 300000, 36, 12.0, '2009-07-19', 1200),
(2, 'S.P. Sharma', 500000, 48, 10.0, '2008-03-22', 1800),
(3, 'K.P. Jain', 300000, 48, None, '2008-07-03', 1600),
(4, 'M.P. Yadav', 200000, 60, 12.0, '2008-12-05', 2250),
(5, 'S.P. Sinha', 700000, 60, 12.5, '2008-06-05', 3000),
(6, 'P. Sharma', 700000, 60, 12.5, '2008-03-05', 3800),
(7, 'K.S. Dhall', 1000000, 60, None, '2008-03-05', 3800)
]

insert_query = '''
INSERT INTO LOANS (AccNo, Cust_Name, Loan_Amount, Installments,
Int_Rate, Start_Date, Interest)
VALUES (%s, %s, %s, %s, %s, %s, %s)
'''

cursor.executemany(insert_query, loans_data)

# Commit changes and close connection


Ojas Srivastava 12th - Aryabhatta 2024-25

connection.commit()
cursor.close()
connection.close()

print("Database and table created, data inserted successfully.")

Output –

Q33 -

Code –
import mysql.connector

# Connect to MySQL server


connection =
mysql.connector.connect(host="localhost",user="root",password="1234")

cursor = connection.cursor()
Ojas Srivastava 12th - Aryabhatta 2024-25

cursor.execute("CREATE DATABASE IF NOT EXISTS HOTEL_DB")


cursor.execute("USE HOTEL_DB")

cursor.execute("CREATE TABLE IF NOT EXISTS HOTEL (EMPID VARCHAR(10)


PRIMARY KEY, CATEGORY VARCHAR(20), SALARY INT)")

hotel_data = [('E101', 'MANAGER', 60000),('E102', 'EXECUTIVE', 65000),


('E103', 'CLERK', 40000),('E104', 'MANAGER', 62000),('E105', 'EXECUTIVE',
50000),('E106', 'CLERK', 35000)]

insert_query = "INSERT INTO HOTEL (EMPID, CATEGORY, SALARY) VALUES


(%s, %s, %s)"
cursor.executemany(insert_query, hotel_data)

connection.commit()
cursor.close()
connection.close()

Output –

Q34 –
Ojas Srivastava 12th - Aryabhatta 2024-25

Code –
import mysql.connector
connection = mysql.connector.connect(
host="localhost",
user="root",
password="1234",
database="PRODUCT_CLIENT_DB"
)

cursor = connection.cursor()

# Queries for subparts


queries = {
"i": "SELECT * FROM CLIENT WHERE City='Delhi';",
"ii": "SELECT * FROM PRODUCT WHERE Price BETWEEN 50 AND 100;",
"iii": "SELECT * FROM PRODUCT WHERE ProductName LIKE '%Wash';",
"iv": "SELECT DISTINCT City FROM CLIENT;",
"v": "SELECT Manufacturer, MAX(Price), MIN(Price), COUNT(*) FROM
PRODUCT GROUP BY Manufacturer;",
"vi": "SELECT ProductName, Price * 4 AS PriceMultiplied FROM PRODUCT;"
}

# Execute and display results


for key, query in queries.items():
print(f"Results for Query {key}:")
cursor.execute(query)
for row in cursor.fetchall():
Ojas Srivastava 12th - Aryabhatta 2024-25

print(row)
print("\n")

# Close connection
cursor.close()
connection.close()

Output –
Ojas Srivastava 12th - Aryabhatta 2024-25
Ojas Srivastava 12th - Aryabhatta 2024-25

You might also like