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

c.s Practical File Hassium Class 12[1]

Uploaded by

aryansingh.94544
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
18 views

c.s Practical File Hassium Class 12[1]

Uploaded by

aryansingh.94544
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 30

Delhi public school, Vindhyanagar

Session – 2024-25
Subject – Computer science

Computer Science Practical File

Submitted By – Aryan Singh


Class – 12th
Section – ‘C’
Roll number –11
Guided by – Mrs. Revathi

___________ ___________
Signature of Student Signature of
Teacher Remarks
INDEX: -

1. Program to read and display file content line


by line with each word separated by “ #”.
2. Program to read the content of file and display
the total number of consonants, uppercase,
vowels and lower case characters.

3.Remove all the lines that contain the character


'a' in a file and write it to another file.
4.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.
5.Create a binary file with roll number, name and
marks. Input a roll number and update the
marks.
6.Write a random number generator that
generates random numbers between 1 and 6
(simulates a dice).
7.Write a Python program to implement a stack
using list.
8.Create a CSV file by entering user-id and
password, read and search the password for
given userid.
9.Database Management
● Create a student table and insert data.
10.Implement the following SQL commands on
the student table:
o ALTER table to add new attributes / modify data
type / drop attribute
o UPDATE table to modify data
o ORDER By to display data in ascending /
descending order
o DELETE to remove tuple(s)
o GROUP BY and find the min, max, sum, count
and average
11.Consider the following DEPT and EMPLOYEE
tables. Write SQL queries for (1) to (4) and find
outputs for SQL queries (5) to (8).
12.Write a program with a function that takes an
integer and prints the number that follows after
it. Call the function with these arguments :
4, 6, 8, 2 + 1, 4 - 3 * 2, -3 -2
13. Write a function that takes amount-in-dollars
and dollar-to-rupee conversion price; it then
returns the amount converted to rupees. Create
the function in both void and non-void forms.
14.Write a program that generates a series using
a function which takes first and last values of the
series and then generates four terms that are
equidistant e.g., if two numbers passed are 1 and
7 then function returns 1 3 5 7.
15. Write a program that reads a text file and
creates another file that is identical except that
every sequence of consecutive blank spaces is
replaced by a single space.
16. Write a method in python to read lines from a
text file MYNOTES.TXT, and display those lines,
which are starting with an alphabet 'K'.
17. Create a binary file student.dat to hold
students’ records like Rollno., Students name,
and Address using the list. Write functions to
write data, read them, and print on the screen.
18. Write a program that reads characters from
the keyboard one by one. All lower case
characters get stored inside the file LOWER, all
upper case characters get stored inside the file
UPPER and all other characters get stored inside
file OTHERS.
19. A binary file “Book.dat” has structure
[BookNo, Book_Name, Author, Price].
i. Write a user defined function CreateFile() to
input data for a record and add to Book.dat .
ii. Write a function CountRec(Author) in Python
which accepts the Author name as parameter and
count and return number of books by the given
Author are stored in the binary file “Book.dat”
20. ABC School has allotted unique token IDs
from (1 to 600) to all the parents for facilitating a
lucky draw on the day of their Annual day
function. The winner would receive a special
prize. Write a program using Python that helps to
automate the task.(Hint: use random module)
21. Consider the following table named "GYM"
with details about fitness items being sold in the
store. Write command of SQL for (i) to (iv).
(i) To display the names of all the items whose
name starts with "A".
(ii) To display ICODEs and INAMEs of all items,
whose Brandname is Reliable or Coscore.
(iii) To change the Brandname to "Fit Trend India"
of the item, whose ICODE as "G101".
(iv) Add a new row for new item in GYM with the
details :
"G107", "Vibro exerciser", 21000, "GTCFitness
1. Program to read and display file content
line by line with each word separated by “
#”.
myfile=open(“Answer.txt”,”r”)
line=“”
while line :
line=myfile.readline()
for word in line.split():
print(word,end=”#”)
print()
myfile.close()

IF THE CONTENT OF FILE IS:


I AM USING PYTHON
OUTPUT:
I#AM #USING#PYTHON#

2. Program to read the content of file and


display the total number of consonants,
uppercase, vowels and lower case
characters.
filein = open("Mydoc1.txt",'r')
line = filein.read()
count_vow = 0
count_con = 0
count_low = 0
count_up = 0
count_digit = 0
count_other = 0
print(line)
for ch in line:
if ch.isupper():
count_up +=1
if ch.islower():
count_low += 1
if ch in 'aeiouAEIOU':
count_vow += 1
if ch.isalpha():
count_con += 1
if ch.isdigit():
count_digit += 1
if not ch.isalnum() and ch !=' ' and ch !='\n':
count_other += 1
print("Digits",count_digit)
print("Vowels: ",count_vow)
print("Consonants: ",count_con-count_vow)
print("Upper Case: ",count_up)
print("Lower Case: ",count_low)
print("other than letters and digit: ",count_other)
filein.close()
OUTPUT:
Digits: 13
Vowels: 20
Consonants: 50
Upper Case: 9
Lower Case: 34
Other than letters and digits : 0
3. Remove all lines that contain the character 'a'
in a file and write it to another file.
def remove_lines_with_a(input_file, output_file):
with open(input_file, 'r') as infile:
lines = infile.readlines()

with open(output_file, 'w') as outfile:


for line in lines:
if 'a' not in line:
outfile.write(line)

# Example usage
remove_lines_with_a('input.txt', 'output.txt')
4. 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

# Function to create a binary file with student


data
def create_binary_file(filename):
students = [
('John Doe', 101),
('Jane Smith', 102),
('Alice Johnson', 103),
]
with open(filename, 'wb') as file:
pickle.dump(students, file)

# Function to search by roll number


def search_roll_number(filename, roll_number):
with open(filename, 'rb') as file:
students = pickle.load(file)
for name, roll in students:
if roll == roll_number:
print(f'Name: {name}, Roll Number:
{roll}')
return
print('Roll number not found')

# Example usage
create_binary_file('students.bin')
search_roll_number('students.bin', 102)
5. Create a binary file with roll number, name and
marks. Input a roll number and update the
marks.
import pickle

# Function to create a binary file with student


data
def create_student_file(filename):
students = [
(101, 'John Doe', 85),
(102, 'Jane Smith', 92),
(103, 'Alice Johnson', 76),
]

with open(filename, 'wb') as file:


pickle.dump(students, file)

# Function to update marks based on roll number


def update_marks(filename, roll_number,
new_marks):
with open(filename, 'rb') as file:
students = pickle.load(file)

for i, (roll, name, marks) in


enumerate(students):
if roll == roll_number:
students[i] = (roll, name, new_marks)
break
else:
print('Roll number not found')
return

with open(filename, 'wb') as file:


pickle.dump(students, file)

# Example usage
create_student_file('students_with_marks.bin')
update_marks('students_with_marks.bin', 102,
95)
6. Write a random number generator that
generates random numbers between 1 and 6
(simulates a dice).
import random

def roll_dice():
return random.randint(1, 6)

# Example usage
print(f'Rolled: {roll_dice()}')
7. Write a Python program to implement a stack
using list.
class Stack:
def __init__(self):
self.stack = []

def push(self, item):


self.stack.append(item)

def pop(self):
if len(self.stack) > 0:
return self.stack.pop()
else:
return "Stack is empty"

def peek(self):
if len(self.stack) > 0:
return self.stack[-1]
else:
return "Stack is empty"

def is_empty(self):
return len(self.stack) == 0

def size(self):
return len(self.stack)

# Example usage
stack = Stack()
stack.push("John")
stack.push("Alice")
print(stack.pop()) # Alice
print(stack.peek()) # John
8. Create a CSV file by entering user-id and
password, read and search the password for a
given user-id.
import csv

# Function to create a CSV file with user-id and


password
def create_csv_file(filename):
data = [
('user1', 'password123'),
('user2', 'password456'),
('user3', 'password789'),
]

with open(filename, 'w', newline='') as file:


writer = csv.writer(file)
writer.writerow(['User-ID', 'Password'])
writer.writerows(data)

# Function to search for password by user-id


def search_password(filename, user_id):
with open(filename, 'r') as file:
reader = csv.reader(file)
next(reader) # Skip header
for row in reader:
if row[0] == user_id:
return row[1]
return 'User ID not found'

# Example usage
create_csv_file('users.csv')
print(search_password('users.csv', 'user2'))
9. Database Management: Create a student table
and insert data.
-- SQL script to create a student table and insert
data
CREATE TABLE Student (
RollNo INT PRIMARY KEY,
Name VARCHAR(100),
Age INT,
Marks INT
);

-- Insert data into the table


INSERT INTO Student (RollNo, Name, Age, Marks)
VALUES (101, 'John Doe', 20, 85);
INSERT INTO Student (RollNo, Name, Age, Marks)
VALUES (102, 'Jane Smith', 22, 92);
INSERT INTO Student (RollNo, Name, Age, Marks)
VALUES (103, 'Alice Johnson', 21, 76);
10. Implement the following SQL commands on
the student table:
-- ALTER TABLE: Add a new column
ALTER TABLE Student ADD COLUMN Address
VARCHAR(255);

-- ALTER TABLE: Modify data type of Marks


column
ALTER TABLE Student MODIFY COLUMN Marks
DECIMAL(5,2);

-- ALTER TABLE: Drop a column


ALTER TABLE Student DROP COLUMN Age;

-- UPDATE: Modify data


UPDATE Student SET Marks = 90 WHERE RollNo =
101;

-- ORDER BY: Display students ordered by Marks


in descending order
SELECT * FROM Student ORDER BY Marks DESC;

-- DELETE: Remove a student by Roll Number


DELETE FROM Student WHERE RollNo = 103;

-- GROUP BY: Find the minimum, maximum, sum,


count, and average of Marks
SELECT MIN(Marks) AS MinMarks, MAX(Marks) AS
MaxMarks, SUM(Marks) AS TotalMarks, COUNT(*)
AS StudentCount, AVG(Marks) AS AverageMarks
FROM Student;
11. Write a function push (student) and pop
(student) to add and remove students from a list,
considering them as stack operations.
class Stack:
def __init__(self):
self.stack = []

def push(self, student):


self.stack.append(student)
print(f'{student} added to the stack')

def pop(self):
if self.stack:
student = self.stack.pop()
print(f'{student} removed from the
stack')
else:
print('Stack is empty')

# Example usage
student_stack = Stack()
student_stack.push('John Doe')
student_stack.push('Alice Johnson')
student_stack.pop() # Alice Johnson removed
11.Consider the following DEPT and EMPLOYEE
tables. Write SQL queries for (1) to (4) and find
outputs for SQL queries (5) to (8).

i. To display Eno, Name, and Gender from the


table EMPLOYEE in ascending order of Eno.
SELECT Eno, Name, Gender
FROM EMPLOYEE
ORDER BY Eno ASC;
ii. To display the Name of all the MALE employees
from the table EMPLOYEE.
SELECT Name
FROM EMPLOYEE
WHERE Gender = 'MALE';

iii. To display the Eno and Name of those


employees from the table EMPLOYEE who are
born between '1997-01-01' and '1999-12-01'.
SELECT Eno, Name
FROM EMPLOYEE
WHERE DOB BETWEEN '1997-01-01' AND '1999-
12-01';

iv. To count and display FEMALE employees who


have joined after '1999-01-01'.
SELECT COUNT(*) AS FemaleEmployees
FROM EMPLOYEE
WHERE Gender = 'FEMALE' AND DOJ > '1999-01-
01';

v. To display the count of employees in each


department (DCODE) where the number of
employees is greater than 1.
SELECT COUNT(*), DCODE
FROM EMPLOYEE
GROUP BY DCODE
HAVING COUNT(*) > 1;
vi. To display distinct DEPARTMENT names from
the table DEPT.
SELECT DISTINCT DEPARTMENT
FROM DEPT;

vii. To display Name and Department from the


EMPLOYEE and DEPT tables where the DCODE
matches, and Eno is less than 1113.
SELECT E.Name, D.Department
FROM EMPLOYEE E
JOIN DEPT D ON E.DCODE = D.DCODE
WHERE E.Eno < 1113;

vii. To display the MAX(DOJ) (Date of Joining) and


MIN(DOB) (Date of Birth) from the table
EMPLOYEE.
SELECT MAX(DOJ) AS MaxDOJ, MIN(DOB) AS
MinDOB
FROM EMPLOYEE;

12. Write a program with a function that takes an


integer and prints the number that follows after
it. Call the function with these arguments: 4, 6,
8, 2 + 1, 4 - 3 * 2, -3 -2
def print_next_number(num):
print(num + 1)
# Calling the function with given arguments
print_next_number(4) # Output: 5
print_next_number(6) # Output: 7
print_next_number(8) # Output: 9
print_next_number(2 + 1) # Output: 4 (2 + 1 = 3,
and 3 + 1 = 4)
print_next_number(4 - 3 * 2) # Output: -1 (4 - 6 =
-2, and -2 + 1 = -1)
print_next_number(-3 - 2) # Output: -5 (-3 - 2 = -
5, and -5 + 1 = -4)

13. Write a function that takes amount in dollars


and dollar-to-rupee conversion price; it then
returns the amount converted to rupees. Create
the function in both void and non-void forms.
# Non-void function (returns the converted
value)
def convert_to_rupees(amount_dollars,
conversion_rate):
return amount_dollars * conversion_rate

# Void function (prints the converted value)


def convert_to_rupees_void(amount_dollars,
conversion_rate):
converted_amount = amount_dollars *
conversion_rate
print(f"Converted Amount:
{converted_amount} Rupees")
# Example usage
usd_amount = 100
rate = 82.5 # Dollar to Rupee conversion rate

# Non-void function
converted = convert_to_rupees(usd_amount,
rate)
print(f"Converted Amount: {converted} Rupees")

# Void function
convert_to_rupees_void(usd_amount, rate)

14. Write a program that generates a series


using a function which takes first and last values
of the series and then generates four terms that
are equidistant. For example, if two numbers
passed are 1 and 7, then the function returns 1,
3, 5, 7.
def generate_series(first, last):
step = (last - first) // 3 # Equidistant, so divide
by 3 for 4 terms
series = [first + i * step for i in range(4)]
print("Generated series:", series)

# Example usage
generate_series(1, 7) # Output: [1, 3, 5, 7]
15. Write a program that reads a text file and
creates another file that is identical except that
every sequence of consecutive blank spaces is
replaced by a single space.
def replace_blank_spaces(input_file, output_file):
with open(input_file, 'r') as infile:
content = infile.read()

# Replace sequences of spaces with a single


space
updated_content = ' '.join(content.split())

with open(output_file, 'w') as outfile:


outfile.write(updated_content)

# Example usage
replace_blank_spaces('input.txt', 'output.txt')

16. Write a method in Python to read lines from a


text file MYNOTES.TXT, and display those lines,
which are starting with an alphabet 'K'.
def display_lines_starting_with_k(filename):
with open(filename, 'r') as file:
for line in file:
if line.strip().startswith('K'):
print(line.strip())
# Example usage
display_lines_starting_with_k('MYNOTES.TXT')

17. Create a binary file student.dat to hold


students’ records like Rollno., Student's name,
and Address using a list. Write functions to write
data, read them, and print on the screen.
import pickle

# Function to write student records to a binary


file
def write_student_data(filename):
students = [
(101, 'John Doe', '1234 Elm St'),
(102, 'Jane Smith', '5678 Oak St'),
(103, 'Alice Johnson', '9101 Pine St'),
]
with open(filename, 'wb') as file:
pickle.dump(students, file)

# Function to read student data from the binary


file
def read_student_data(filename):
with open(filename, 'rb') as file:
students = pickle.load(file)
for student in students:
print(f"Roll No: {student[0]}, Name:
{student[1]}, Address: {student[2]}")

# Example usage
filename = 'student.dat'

# Write data to binary file


write_student_data(filename)

# Read and print data from binary file


read_student_data(filename)

18. Write a program that reads characters from


the keyboard one by one. All lowercase
characters get stored inside the file LOWER, all
uppercase characters get stored inside the file
UPPER, and all other characters get stored inside
file OTHERS.
def classify_and_store_characters():
while True:
char = input("Enter a character (or 'quit' to
stop): ")
if char.lower() == 'quit':
break
if char.islower():
with open('LOWER.txt', 'a') as lower_file:
lower_file.write(char + '\n')
elif char.isupper():
with open('UPPER.txt', 'a') as upper_file:
upper_file.write(char + '\n')
else:
with open('OTHERS.txt', 'a') as others_file:
others_file.write(char + '\n')

# Example usage
classify_and_store_characters()

19. A binary file “Book.dat” has structure


[BookNo, Book_Name, Author, Price].
i. Write a user-defined function CreateFile() to
input data for a record and add to Book.dat.
import pickle

# Function to create a binary file and add book


records
def create_file(filename):
with open(filename, 'wb') as file:
while True:
book_no = int(input("Enter Book Number
(0 to stop): "))
if book_no == 0:
break
book_name = input("Enter Book Name: ")
author = input("Enter Author Name: ")
price = float(input("Enter Price: "))
book_record = (book_no, book_name,
author, price)
pickle.dump(book_record, file)

# Example usage
create_file('Book.dat')
ii. Write a function CountRec(Author) in Python
which accepts the Author name as a parameter
and counts and returns the number of books by
the given Author stored in the binary file
Book.dat.
import pickle

# Function to count the number of books by a


specific author in the binary file
def count_rec(filename, author_name):
count = 0
try:
with open(filename, 'rb') as file:
while True:
try:
book_record = pickle.load(file)
if book_record[2].lower() ==
author_name.lower():
count += 1
except EOFError:
break
except FileNotFoundError:
print(f"File '{filename}' not found.")
return count

# Example usage
author = input("Enter Author Name to search: ")
book_count = count_rec('Book.dat', author)
print(f"Number of books by {author}:
{book_count}")

20. ABC School has allotted unique token IDs


from (1 to 600) to all the parents for facilitating a
lucky draw on the day of their Annual day
function. Write a program using Python that
helps to automate the task. (Hint: use the
random module)
import random

def lucky_draw():
# Token IDs are from 1 to 600
token_ids = list(range(1, 601))
# Randomly select a token ID
winner_token = random.choice(token_ids)
print(f"The winner of the lucky draw is Token
ID: {winner_token}")

# Example usage
lucky_draw()

21. Consider the following table named "GYM"


with details about fitness items being sold in the
store. Write command of SQL for (i) to (iv).

(i) To display the names of all the items whose


name starts with "A".
SELECT INAME
FROM GYM
WHERE INAME LIKE 'A%';

(ii) To display ICODEs and INAMEs of all items,


whose Brandname is Reliable or Coscore.
SELECT ICODE, INAME
FROM GYM
WHERE BRANDNAME IN ('Reliable', 'Coscore');

(iii) To change the Brandname to "Fit Trend India"


of the item, whose ICODE is "G101".
UPDATE GYM
SET BRANDNAME = 'Fit Trend India'
WHERE ICODE = 'G101';

(iv) Add a new row for a new item in GYM with


the details: "G107", "Vibro exerciser", 21000,
"GTCFitness"
INSERT INTO GYM (ICODE, INAME, PRICE,
BRANDNAME)
VALUES ('G107', 'Vibro exerciser', 21000,
'GTCFitness');

You might also like