Neeraj
Neeraj
COMPUTER SCIENCE
PRACTICAL FILE
Session 2023-24
Roll No: 40
Practical File
Of
Computer Science
2
INDE
X
Sr Pg
No. Practicals No.
3
Write a python program to read a text file and display each
7
word separated by ‘#’
Take a sample text file and find the most commonly occuring
7 11
word and frequency of all words.
8 Create a binary file with roll no. , name and marks. Input a roll 12
no. to change marks.
10 Create a binary file with name and roll no. and for a given roll no. 14
display the name if not found3display appropriate message.
2
Sr Pg
No. Practicals No.
Create a csv file with employ ID, name and mobile no. update the
11 15
record by searching with employ ID and display the record.
appropriate message.
3
Q1.
Write a python program to input 3 numbers and display the largest , smallest number.
"OUTPUT"
5
Q2.
Write a python program to input a number and check if the number is prime or not.
"OUTPUT"
6
Q3.
Write a python program to read a text file and display each word separated by ‘#’
f = open("files.txt",'r')
read = f.readlines()
for i in read:
n= i.split()
for j in n:
print(j,'#',end="")
print()
f.close()
"OUTPUT"
7
Q4.
Write a python program to read a file and display the nuber of vowels, consonants, uppercase,
lowercase.
f = open("files.txt", 'r')
content = f.read()
vowels = ['a', 'e', '1', '0', 'u', 'A', 'E', '1', '0', 'U']
total_vowels = 0
total_upper = 0
total_lower = 0
print("Vowels:", total_vowels,
"Uppercase:", total_upper,
"Lowercase:", total_lower)
f.close()
"OUTPUT"
8
Q5.
Write a python program to remove the character ‘a’ in a line and write it to another file.
f = open("files.txt", 'r')
sir = f.read()
nl = sir.replace('a', ' ')
fx = open('fold.txt', 'w')
fx.write(nl)
print(nl)
f.close()
fx.close()
"OUTPUT"
9
Q6.
Write a python program to create a binary file with employee no., salary and employ ID and
display the data on the screen.
def pro6():
import pickle
def write():
f = open("emp.dat", 'ab')
data = list()
empName = str(input("Name: "))
empId = int(input("ID: "))
empSalary = int(input("Salary in rs: "))
data.append({"Name": empName, "ID": empId, "Salary": empSalary})
pickle.dump(data, f)
f.close()
def read():
f = open("emp.dat", 'rb')
l = pickle.load(f)
print(l)
for i in l:
print('\t', "Name: ", i['Name'], '\n',
'\t', "ID: ", i['ID'], '\n',
'\t', "Salary: ", i['Salary'])
f.close()
write()
read()
pro6()
"OUTPUT"
10
Q7.
Take a sample text file and find the most commonly occuring word and frequency of all words.
inputFile = "files.txt"
pro = []
f = open('files.txt', 'r')
for i in f:
w = i.split()
for j in w:
pro.append(j)
for k in cs:
if cs[k] > raj:
raj = cs[k]
m = k
print("{", m, "} is the most repeated word in the text file", '\n', '\t', "Frequency of all words", cs)
f.close()
"OUTPUT"
11
Q8.
Create a binary file with roll no. , name and marks. Input a roll no. to change marks.
import pickle
def pro8():
f = open("student.dat", "ab+")
dataDumptoF = {}
def entry():
dataDumptoF["Name"] = str(input("Enter Student name: "))
dataDumptoF["RollNo"] = int(input("Enter roll no: "))
dataDumptoF["Marks"] = float(input("Enter Student Marks: "))
pickle.dump(dataDumptoF, f)
def searchChange():
j = f.tell()
f.seek(0)
l = pickle.load(f)
print(l)
rollNo = int(input("enter the roll no to search: "))
if (l["RollNo"] == rollNo):
l["Marks"] = float(input("Enter marks to be updated: "))
f.seek(j)
pickle.dump(l, f)
print("Student marks updated successfully")
print(l)
else:
print("Roll no. doesn't exist")
entry()
searchChange()
pro8()
"OUTPUT"
12
Q9.
Write a python program for a random number genrator that generates a random number
between 1-6.
import random
for i in range(0,6):
print(random.randint(1,6))
"OUTPUT"
13
Q10.
Create a binary file with name and roll no. and for a given roll no. display the name if
not found display appropriate message.
import pickle
def pro10():
f = open("school.dat",
"ab+") dataDumptoF = {}
def entry():
dataDumptoF["Name"] = str(input("Enter Student name:
")) dataDumptoF["RollNo"] = int(input("Enter roll no:
"))
pickle.dump(dataDumptoF, f)
def search():
f.seek(0)
l = pickle.load(f)
print(l)
rollNo = int(input("enter the roll no to search:
")) if (l["RollNo"] == rollNo):
print(l["Name"])
else:
print("Roll no. doesn't exist")
entry()
search()
f.close()
pro10()
"OUTPUT"
14
Q11. Create a csv file with employ ID, name and mobile no. update the record by searching with
employ ID and display the record.
import csv
def printEmpRecords(empList):
for i, emp in enumerate(empList, start=1):
if len(emp) > 2:
print("Record", i, '\n', '\tName:', emp[0], '\n', '\tID:', emp[1], '\n', '\tMobile no.:', emp[2])
# Main program
with open('emp.csv', 'a') as f:
l = csv.writer(f)
while True: "OUTPUT
name = input("Name: ")
id = int(input("ID: ")) "
mNum = int(input("Mobile no.: "))
rowsList = [[name, id, mNum]]
l.writerows(rowsList)
printEmpRecords(empData)
if indexToEdit != -1:
print("Editing record for ID", sID)
editEmpRecord(empData, indexToEdit)
print("Updated records:")
printEmpRecords(empData)
else:
print("Employee with ID", {sID}, "not found.")
15
Q12.
Create a csv file by entering user id and password search and display the password for a given
used id.
import csv
def printUserRecords(userList):
for i, user in enumerate(userList, start=1):
if len(user) >= 2:
print(f"Record {i}\n\tUser ID: {user[0]}\n\tPassword: {user[1]}\n")
else:
print(f"Record {i} is incomplete and cannot be printed.\n")
# Main program
with open('users.csv', 'a', newline='') as f:
l = csv.writer(f)
numUsers = int(input("Number of users: "))
userRecords = []
for _ in range(numUsers):
userID = int(input("User ID: "))
password = input("Password: ")
userRecords.append([userID, password])
l.writerows(userRecords)
if userData and len(userData[0]) >= 2: # Check if the list is not empty and has at least two columns
printUserRecords(userData)
if indexToEdit != -1:
print(f"User with User ID {sID} found.\nUser ID: {userData[indexToEdit][0]}\nPassword: {userData[indexToEdit][1]}")
else:
print(f"User with User ID {sID} not found.")
else:
print("No user records found.")
"OUTPUT"
16
Q13.
Write a python program to create and search student record in csv file.
import csv
def printStRecords(stList):
for i, st in enumerate(stList, start=1):
print("Record ", i)
print('\tName: ', st[0], '\n\tClass: ', st[1], '\n\tRoll Number:', st[2])
# Main program
with open('students.csv', 'a', newline='') as f:
l = csv.writer(f)
numSt = int(input("Number of Students: "))
stRecords = []
for _ in range(numSt):
name = input("Name: ")
cl = int(input("Class: "))
rollNo = int(input("Roll No.: "))
stRecords.append([name, cl, rollNo])
l.writerows(stRecords)
printStRecords(stData)
if indexToEdit != -1:
print("Student with Roll Number ", rollNo, "found.")
print("Name: ", stData[indexToEdit][0], '\nClass: ', stData[indexToEdit][1], '\nRoll Number: ', stData[indexToEdit][2])
else:
print("Student with Roll Number ", rollNo, "not found.")
"OUTPUT"
17
Q14.
Write a python program to implement a stack using push and pop operation on stack.
stack = list()
def isEmpty(stack):
if len(stack) == 0:
return True
else:
return False
def pop(stack):
if isEmpty(stack):
print("Empty Stack")
return None
else:
stack.pop()
def display(stack):
l = len(stack)
for i in range(l-1, -1, -1):
print(stack[i])
push(stack, "Neeraj")
display(stack)
"OUTPUT"
18
Q15.
Write a python program using function push(arr) where arr is a list of numbers. From this
list push all the numbers that are divisible by 5 into a stack implemented using a list. Display the
stack if it has atleast one element otherwise display appropriate message.
def push(arr):
stack = []
for num in arr:
if num % 5 == 0:
stack.append(num)
return stack
def display_stack(stack):
if len(stack) == 1:
print("The stack has one element:", stack[0])
elif len(stack) > 1:
print("The stack contains the following elements:")
for element in stack:
print(element)
else:
print("The stack is empty.")
result_stack = push(numbers)
display_stack(result_stack)
"OUTPUT"
19
Q16.
Write a Python Program to integrate MYSQL with Python to create Database and
Table to store the details of employees.
import mysql.connector
def create_db():
con = None # Initialize con to None
try:
con = mysql.connector.connect(host='localhost', user='root', password='87654321')
if con.is_connected():
cur =
con.cursor()
q = "CREATE DATABASE IF NOT EXISTS employees"
cur.execute(q)
print("Employees database created successfully")
finally:
if con is not
None:
con.close()
def create_table():
con = None # Initialize con to None
try:
con = mysql.connector.connect(host='localhost', user='root', password='87654321', database='employees')
if con.is_connected():
cur =
con.cursor()
q = "CREATE TABLE IF NOT EXISTS emp (EMPNO INT PRIMARY KEY, ENAME VARCHAR(20), GENDER VARCHAR(3), SALARY INT)"
cur.execute(q)
print('Emp Table created successfully')
finally:
"OUTPUT"
if con is not
None:
con.close()
ch = 'y'
")) if opt == 1:
create_db()
elif opt == 2:
create_table()
else:
print("Invalid Choice")
import mysql.connector
if con.is_connected():
cur = con.cursor()
opt = 'y'
cur.execute(Query, values)
con.commit()
opt = input("Do you want to add another employee details (y/n): ")
data = cur.fetchall()
for i in data:
print(i)
con.close()
"OUTPUT"
21
Q18.
Write a Python Program to integrate MYSQL with Python to search an Employee using
EMPID and display the record if present in already existing table EMP, if not display the
appropriate message.
import mysql.connector
if con.is_connected():
cur = con.cursor()
cur.execute(Query)
data = cur.fetchone()
con.close()
"OUTPUT"
22
Q19.
Write a Python Program to integrate MYSQL with Python to search an Employee
using EMPID and update the Salary of an employee if present in already existing
table
EMP, if not display the appropriate message.
import mysql.connector
if con.is_connected():
cur = con.cursor()
Eno={}".format(Eno)
cur.execute(Query)
data = cur.fetchone()
ans = input("Do you want to update the Salary of the above employee
for i in data:
print(i)
else:
print("Record not Found!!!")
con.close()
"OUTPUT"
23
SQL COMMANDS EXERCISE - 1
Ex.No: 20
DATE:
AIM: Q20.
To write Queries for the following Questions based on the given table:
USE STUDENTS;
SHOW DATABASES;
(e) Write a Query to List all the tables that exists in the current database.
SHOW TABLES;
Output:
3
24
SQL COMMANDS EXERCISE - 2
Ex.No: 21
DATE:
AIM: Q21.
To write Queries for the following Questions based on the given table:
(a) Write a Query to insert all the rows of above table into Info table.
(b) Write a Query to display all the details of the Employees from the above table 'STU'.
Output:
3
25
(c) Write a query to Rollno, Name and Department of the students from STU table.
Output:
Output:
Output:
********************************************************************************************
26
3
Ex.No: 22 SQL COMMANDS EXERCISE - 3
DATE:
AIM:
Q22.
To write Queries for the following Questions based on the given table:
Output:
(b) Write a Query to list name of the students whose ages are between 18 to 20.
Output:
3
27
(c) Write a Query to display the name of the students whose name is starting with 'A'.
Output:
(d) Write a query to list the names of those students whose name have second alphabet 'n' in their
names.
Output:
**********************************************************************************************************
28
3
Ex.No: 23 SQL COMMANDS EXERCISE - 4
DATE:
AIM:
Q23.
To write Queries for the following Questions based on the given table:
(b) Write a Query to change the fess of Student to 170 whose Roll number is 1, if the existing fess
is less than 130.
Output(After Update):
4
29
(c) Write a Query to add a new column Area of type varchar in table STU.
Output:
(d) Write a Query to Display Name of all students whose Area Contains NULL.
Output:
(e) Write a Query to delete Area Column from the table STU.
Output:
Output:
*******************************************************************************************
430
Ex.No: 24 SQL COMMANDS EXERCISE - 5
DATE:
AIM: Q24.
To write Queries for the following Questions based on the given table:
TABLE: UNIFORM
TABLE: COST
(a) To Display the average price of all the Uniform of Raymond Company from table COST.
Output:
(b) To display details of all the Uniform in the Uniform table in descending order of Stock date.
Output:
4
31
(c) To Display max price and min price of each company.
Output:
(d) To display the company where the number of uniforms size is more than 2.
Output:
(e) To display the Ucode, Uname, Ucolor, Size and Company of tables uniform and cost.
Output:
*****************************************************************************************
432