0% found this document useful (0 votes)
21 views33 pages

Finally Yy Yyy Yyy

Uploaded by

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

Finally Yy Yyy Yyy

Uploaded by

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

CERTIFICATE

This is to certify that Krush Ranjit Horo of class XII 'A' has
successfully completed the Computer Science project file
under the supervision of Miss Preeti Singh.

He has prepared the project under my guidance and as per the


norms by the CBSE.

Internal Signature External Signature

Principal Signature

1
ACKNOWLEDGEMENT
I would like to express my heartfelt gratitude to my Computer
Science teacher Miss Preeti Singh and Fr. Ignatius Lakra
who gave me the opportunity to do this project, which helped
in doing a lot of research and I came to know about so many
new things. I am very thankful to them.

Secondly, I also want to extend my sincere thanks to my


family and friends for their unwavering support and
motivation throughout this journey.

2
INDEX
SL TITLE PAGE
No. NO.
1 Read a text file line by line and display each word 5
separated a #.
2 Read a text file and display the number of 6-7
vowels/consonants/uppercase/lower case characters in the
file.
3 Remove all the lines that contain the character 'A' in a file 8
and write it to another file
4 Create binary file with the name and roll no, search for a 9-10
given roll no and display the name if not found display
appropriate message.
5 Create a binary file with roll no, name and mark. Input a 11-13
roll no. and update the marks.
6 Write a random number generator that generate random 13
number between 1 and 6.
7 Write a python program to implement stack using list. 14-15
8 Create a CSV file by entering user id and password, read 16-17
and search the password for given user id.
9 Write a python program to implement step operations 18-20
using dictionary.
10 Write a python program to create and search records in 21-22
binary files.
11 Write a python program to perform 23-24
mathematical operations.
12 Write a program to create menu-driven program to find 25-26
factorial and sum of list of numbers using function.
13 Write a python program to implement returning 265
values from function.
14 Write a program to add data to existing data in file. 27
15 Write a program to copy a content of a file to another file. 28
16 Create a student table and insert data. Implement the 29-31
following SQL command on the student table:-
3
1. Alter table to add new attributes modified data
type/drop attribute.
2. Update table to modify data.
3. Order by to display data in ascending/descending
order.
4. Delete to remove tuples. Group by and find the min,
max, sum, count and average.
17 Conclusion 32
18 Bibliography 33

4
1. Read a text file line by line and display each word
separated a #.
Program:

# Open the file in read mode


with open('yourfile.txt', 'r') as file:
# Loop through each line in the file
for line in file:
# Strip any leading/trailing whitespace and split the line into
words
words = line.strip().split()
# Join the words with '#' and print the result
print('#'.join(words))

5
2. Read a text file and display the number of vowels/
consonants/ uppercase/ lower case characters in
the file.
Program:

# Initialize counters for vowels, consonants, uppercase, and


lowercase characters
vowels_count = 0
consonants_count = 0
uppercase_count = 0
lowercase_count = 0

# Define sets of vowels and consonants


vowels = set("AEIOUaeiou")
alphabet = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ
abcdefghijklmnopqrstuvwxyz")

# Open the file in read mode


with open('yourfile.txt', 'r') as file:
# Loop through each character in the file
for line in file:
for char in line:
if char.isalpha(): # Check if the character is alphabetic
if char in vowels:
vowels_count += 1
else:

6
consonants_count += 1
if char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1

# Display the counts


print(f"Vowels: {vowels_count}")
print(f"Consonants: {consonants_count}")
print(f"Uppercase characters: {uppercase_count}")
print(f"Lowercase characters: {lowercase_count}")

7
3. Remove all the lines that contain the character 'A'
in a file and write it to another file.

Program:

# Open the original file in read mode and the new file in write
mode
with open('inputfile.txt', 'r') as infile, open('outputfile.txt', 'w') as
outfile:
# Loop through each line in the input file
for line in infile:
# Check if the line contains 'A'
if 'A' not in line:
# Write the line to the output file if 'A' is not in it
outfile.write(line)

8
4. Create binary file with the name and roll no,
search for a given roll no and display the name if
not found display appropriate message.
Program:

import pickle

# Function to create binary file with student data


def create_binary_file(filename, students):
with open(filename, 'wb') as file:
for student in students:
pickle.dump(student, file) # Write each student
record as binary

# Function to search for a student by roll number


def search_roll_number(filename, roll_no):
found = False
with open(filename, 'rb') as file:
try:
while True:
student = pickle.load(file) # Read each record
if student['roll_no'] == roll_no:
print(f"Name: {student['name']}")
found = True
break
except EOFError:

9
pass # Reached end of file
if not found:
print("Roll number not found.")

# List of students (name and roll number) to add to the file


students = [
{'name': 'Alice', 'roll_no': 101},
{'name': 'Bob', 'roll_no': 102},
{'name': 'Charlie', 'roll_no': 103},
]

# File name for binary file


filename = 'students.dat'
# Create the binary file with student data
create_binary_file(filename, students)

# Example: Search for a roll number


roll_no_to_search = int(input("Enter roll number to search: "))
search_roll_number(filename, roll_no_to_search)

10
5. Create a binary file with roll no, name and mark.
Input a roll no. and update the marks.
Program:

import pickle

# Function to create a binary file with student records


def create_binary_file(filename):
with open(filename, 'wb') as file:
n = int(input("Enter the number of students: "))
for _ in range(n):
roll_no = int(input("Enter roll number: "))
name = input("Enter name: ")
marks = float(input("Enter marks: "))
student = {'roll_no': roll_no, 'name': name, 'marks': marks}
pickle.dump(student, file) # Write each student record as
binary
print("Binary file created successfully.")

# Function to update marks for a given roll number


def update_marks(filename, roll_no_to_update, new_marks):
records = []
updated = False

# Read all records into a list


with open(filename, 'rb') as file:
11
try:
while True:
student = pickle.load(file)
if student['roll_no'] == roll_no_to_update:
student['marks'] = new_marks # Update marks
updated = True
records.append(student)
except EOFError:
pass # End of file reached

# Write all records back to the file with updated marks


with open(filename, 'wb') as file:
for student in records:
pickle.dump(student, file)

if updated:
print(f"Marks updated for roll number {roll_no_to_update}.")
else:
print(f"Roll number {roll_no_to_update} not found.")

# Create the binary file


filename = 'students.dat'
create_binary_file(filename)

# Input roll number and new marks for updating


12
roll_no_to_update = int(input("Enter roll number to update marks:
"))
new_marks = float(input("Enter new marks: "))
update_marks(filename, roll_no_to_update, new_marks)

6. Write a random number generator that generate


random number between 1 and 6 777
Program:

import random

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

# Generate and print a random number


random_number = generate_random_number()
print(random_number)

13
7. Write a python program to implement stack using
list. 777
Program:

class Stack:
def __init__(self):
self.items = []

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

def push(self, item):


self.items.append(item)

def pop(self):
if self.is_empty():
raise IndexError("pop from empty stack")
return self.items.pop()

def peek(self):
if self.is_empty():
raise IndexError("peek from empty stack")
return self.items[-1]
def size(self):
return len(self.items)

14
def __str__(self):
return str(self.items)

# Example usage:
if __name__ == "__main__":
stack = Stack()

stack.push(1)
stack.push(2)
stack.push(3)

print("Current stack:", stack)


print("Top element:", stack.peek())

print("Popped element:", stack.pop())


print("Current stack after pop:", stack)

print("Is stack empty?", stack.is_empty())


print("Stack size:", stack.size())

15
8. Create a CSV file by entering user id and
password, read and search the password for given
user id.
Program:

import csv

# Function to create a CSV file with user ID and password entries


def create_csv(filename):
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['user_id', 'password']) # Header row
while True:
user_id = input("Enter user ID (or 'exit' to stop): ")
if user_id.lower() == 'exit':
break
password = input("Enter password: ")
writer.writerow([user_id, password])
print("CSV file created successfully.")

# Function to search for the password by user ID


def search_password(filename, user_id_to_search):
with open(filename, 'r') as file:
reader = csv.DictReader(file)
for row in reader:

16
if row['user_id'] == user_id_to_search:
print(f"Password for user ID '{user_id_to_search}' is:
{row['password']}")
return
print("User ID not found.")

# Create the CSV file


filename = 'users.csv'
create_csv(filename)

# Search for a password by user ID


user_id_to_search = input("Enter user ID to search for password: ")
search_password(filename, user_id_to_search)

17
9. Write a python program to implement step
operations using dictionary
Program:

class StepManager:
def __init__(self):
self.steps = {}

def add_step(self, step_id, description):


if step_id in self.steps:
print(f"Step {step_id} already exists.")
else:
self.steps[step_id] = description
print(f"Added step {step_id}: {description}")

def update_step(self, step_id, new_description):


if step_id in self.steps:
self.steps[step_id] = new_description
print(f"Updated step {step_id}: {new_description}")
else:
print(f"Step {step_id} not found.")

def get_step(self, step_id):


return self.steps.get(step_id, "Step not found.")

def delete_step(self, step_id):

18
if step_id in self.steps:
del self.steps[step_id]
print(f"Deleted step {step_id}.")
else:
print(f"Step {step_id} not found.")

def list_steps(self):
if not self.steps:
print("No steps available.")
else:
for step_id, description in self.steps.items():
print(f"Step {step_id}: {description}")

# Example usage
if __name__ == "__main__":
manager = StepManager()

while True:
action = input("Choose an action: add, update, get, delete,
list, or exit: ")
if action == 'add':
step_id = input("Enter step ID: ")
description = input("Enter step description: ")
manager.add_step(step_id, description)
elif action == 'update':
step_id = input("Enter step ID to update: ")

19
new_description = input("Enter new description: ")
manager.update_step(step_id, new_description)
elif action == 'get':
step_id = input("Enter step ID to retrieve: ")
print(manager.get_step(step_id))
elif action == 'delete':
step_id = input("Enter step ID to delete: ")
manager.delete_step(step_id)
elif action == 'list':
manager.list_steps()
elif action == 'exit':
break
else:
print("Invalid action. Please choose again.")

20
10. Write a python program to create and search
records in binary files.
Program:

import pickle

# Function to create records in a binary file


def create_records(filename):
with open(filename, 'wb') as file:
n = int(input("Enter the number of students: "))
for _ in range(n):
roll_no = int(input("Enter roll number: "))
name = input("Enter name: ")
marks = float(input("Enter marks: "))
student = {'roll_no': roll_no, 'name': name, 'marks':
marks}
pickle.dump(student, file) # Write each student
record as binary
print("Records have been created successfully.")

# Function to search for a record by roll number


def search_record(filename, roll_no_to_search):
found = False
with open(filename, 'rb') as file:
try:
while True:
student = pickle.load(file)
if student['roll_no'] == roll_no_to_search:
print("Record found:")
print(f"Roll Number: {student['roll_no']}")
print(f"Name: {student['name']}")
print(f"Marks: {student['marks']}")
found = True
break
except EOFError:
pass # End of file reached

21
if not found:
print("Record not found.")

# Main program
filename = 'students.dat'

# Create records
create_records(filename)

# Search for a specific roll number


roll_no_to_search = int(input("Enter roll number to search: "))
search_record(filename, roll_no_to_search)

22
11. Write a python program to perform
mathematical operations.

Program:

def add(x, y):


return x + y

def subtract(x, y):


return x - y

def multiply(x, y):


return x * y

def divide(x, y):


if y == 0:
return "Error: Division by zero is not allowed."
return x / y

def main():
print("Welcome to the Simple Calculator")
print("Select operation:")
print("1. Addition")
print("2. Subtraction")
print("3. Multiplication")
print("4. Division")

23
while True:
choice = input("Enter choice (1/2/3/4 or 'exit' to quit): ")

if choice.lower() == 'exit':
print("Exiting the calculator. Goodbye!")
break

if choice in ('1', '2', '3', '4'):


num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))

if choice == '1':
print(f"{num1} + {num2} = {add(num1, num2)}")

elif choice == '2':


print(f"{num1} - {num2} = {subtract(num1, num2)}")

elif choice == '3':


print(f"{num1} * {num2} = {multiply(num1, num2)}")

elif choice == '4':


print(f"{num1} / {num2} = {divide(num1, num2)}")

else:
print("Invalid input. Please choose a valid operation.")
if _name_ == "_main_":
main()

24
12. Write a program to create menu-driven program
to find factorial and sum of list of numbers using
function.

Program:

import math

def factorial(n):
return math.factorial(n)

def sum_of_list(numbers):
return sum(numbers)

while True:
choice = input("\nChoose (1: Factorial, 2: Sum of List, 3: Exit): ")

if choice == '1':
num = int(input("Enter number: "))
print("Factorial:", factorial(num))

elif choice == '2':


numbers = list(map(int, input("Enter numbers separated by
space: ").split()))
print("Sum:", sum_of_list(numbers))

elif choice == '3':


print("Exiting.")

25
break

else:
print("Invalid choice.")

13. Write a python program to implement returning


values from function.

Program

def add(a, b):


return a + b

def multiply(a, b):


return a * b

num1 = float(input("Enter first number: "))


num2 = float(input("Enter second number: "))

print("Sum:", add(num1, num2))


print("Product:", multiply(num1, num2))

26
14. Write a program to add data to existing data in
file.

Program:

def append_to_file(filename, data):


with open(filename, 'a') as file: # Open the file in append mode
('a')
file.write(data + '\n') # Add the new data and a newline

# Main program
filename = "example.txt"
data = input("Enter data to append to the file: ")
append_to_file(filename, data)

print("Data has been appended to the file.")

27
15. Write a program to copy a content of a file to
another file.

Program:

def copy_file(source_file, destination_file):


with open(source_file, 'r') as src, open(destination_file, 'w') as
dest:
dest.write(src.read()) # Read content from source and write
to destination

# Main program
source_file = "source.txt"
destination_file = "destination.txt"

copy_file(source_file, destination_file)
print(f"Content copied from {source_file} to {destination_file}.")

28
16. Create a student table and insert data.
Implement the following SQL command on the
student table:-
1. Alter table to add new attributes modified data
type/drop attribute
2. Update table to modify data
3. Order by to display data in
ascending/descending order.
4. Delete to remove tuples. Group by and find the
min, max, sum, count and average.

Code:
-- Create the student table
CREATE TABLE student (
id INT PRIMARY KEY,
name VARCHAR(50) NOT NULL,
age INT,
grade DECIMAL(4, 2)
);
-- Insert data into the student table
INSERT INTO student (id, name, age, grade) VALUES (1, 'Alice', 20,
85.5);
INSERT INTO student (id, name, age, grade) VALUES (2, 'Bob', 22,
90.0);
INSERT INTO student (id, name, age, grade) VALUES (3, 'Charlie',
19, 72.5);

29
INSERT INTO student (id, name, age, grade) VALUES (4, 'David', 21,
88.0);
INSERT INTO student (id, name, age, grade) VALUES (5, 'Eve', 20,
91.0);

-- Add a new attribute (column) for email


ALTER TABLE student ADD COLUMN email VARCHAR(100);
-- Modify the data type of an existing attribute (if supported by your
SQL database)
-- For example, changing 'age' to a larger integer or allowing NULL
values
ALTER TABLE student MODIFY COLUMN age SMALLINT;
-- Drop an attribute (column), e.g., removing 'age' from the table
ALTER TABLE student DROP COLUMN age;

-- Update specific data in the table (e.g., add emails to each


student)
UPDATE student SET email = '[email protected]' WHERE name =
'Alice';
UPDATE student SET email = '[email protected]' WHERE name =
'Bob';
UPDATE student SET email = '[email protected]' WHERE name
= 'Charlie';
UPDATE student SET email = '[email protected]' WHERE name
= 'David';
UPDATE student SET email = '[email protected]' WHERE name =
'Eve';

30
-- Display students ordered by grade in ascending order
SELECT * FROM student ORDER BY grade ASC;
-- Display students ordered by grade in descending order
SELECT * FROM student ORDER BY grade DESC;

-- Delete a specific tuple (e.g., delete student Charlie)


DELETE FROM student WHERE name = 'Charlie';

-- Group by a specific attribute, if applicable (e.g., grouping by


email domain if required)
-- For this example, we will use aggregate functions without a
GROUP BYclause
-- Find the minimum grade
SELECT MIN(grade) AS min_grade FROM student;
-- Find the maximum grade
SELECT MAX(grade) AS max_grade FROM student;
-- Find the sum of all grades
SELECT SUM(grade) AS total_grade FROM student;
-- Count the number of students
SELECT COUNT(*) AS student_count FROM student;
-- Find the average grade
SELECT AVG(grade) AS average_grade FROM student;

31
CONCLUSION
Here I have come to the end of the computer science project.
It was a wonderful and learning experience for me while
working on this project. This project took me through various
aspects of project and taught me about research and findings.
It also gave me a real insight into this project topic. I learned
about problem solving and how to deal with challenges. This
project increased my research, thinking skill and interest in
this subject.

Thank you for giving me this project I enjoyed every bit of it.

32
BIBLIOGRAPHY
For successfully completing my project file. I have taken help
from the following website –
https://chatgpt.com/
https://www.mycompiler.io
https://stackoverflow.com
https://www.studocu.com/in/document/kv-ranga-reddy-law-
college/computer-science/cs-practical-programs/44590985

33

You might also like