Computer Science-CLASS-12-RECORD PROGRAMS
Computer Science-CLASS-12-RECORD PROGRAMS
Dhanamjay
1. Read a text file line by line and display each word separated by a #.
# Open the text file for reading
file_path = "your_file.txt" # Replace with the path to your text file
with open(file_path, 'r') as file:
# Read each line in the file
for line in file:
# Split the line into words
words = line.strip().split()
# Join the words with '#' in between and print
result = "#".join(words)
print(result)
OUTPUT:
# Initialize counters
vowels = 0
consonants = 0
uppercase = 0
lowercase = 0
# Define a set of vowels for easy checking
vowel_set = set("AEIOUaeiou")
# Loop through the characters in the text
for char in text:
if char.isalpha():
if char in vowel_set:
vowels += 1
else:
consonants += 1
if char.isupper():
uppercase += 1
elif char.islower():
lowercase += 1
# Display the counts
print("Number of vowels:", vowels)
print("Number of consonants:", consonants)
print("Number of uppercase characters:", uppercase)
print("Number of lowercase characters:", lowercase) Prepared By:K.Dhanamjay
your_file.txt
OUTPUT:
# Open the input file for reading and the output file for writing
with open(input_file_path, 'r') as input_file, open(output_file_path, 'w') as output_file:
for line in input_file:
# Check if the line contains the character 'a'
if 'a' not in line.lower(): # Use .lower() to make it case-insensitive
output_file.write(line)
input.txt
OUTPUT:
Output.txt
Prepared By:K.Dhanamjay
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 name and roll number
def create_binary_file(file_name):
data = [] # Initialize an empty list to store records
# Function to search for a roll number and display the corresponding name
def search_roll_number(file_name, roll_number):
try:
with open(file_name, 'rb') as file:
data = pickle.load(file)
for name, rn in data:
if rn == roll_number:
print("Name:", name)
break
else:
print("Roll number not found.")
except FileNotFoundError:
print("File not found. Please create the binary file first.")
if __name__ == "__main__":
file_name = "student_data.dat" # You can change the filename if needed
create_binary_file(file_name) # Create the binary file
search_roll_number(file_name, "123") # Replace "123" with the roll number you want to search for
OUTPUT:
Prepared By:K.Dhanamjay
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 roll number, name, and marks
def create_binary_file(file_name):
data = [] # Initialize an empty list to store records
# Get user input for records
while True:
roll_number = input("Enter roll number (or type 'exit' to finish): ")
if roll_number == 'exit':
break
name = input("Enter name: ")
marks = input("Enter marks: ")
data.append((roll_number, name, marks))
# Write the data to the binary file
with open(file_name, 'wb') as file:
pickle.dump(data, file)
print("Data saved to", file_name)
# Function to update marks for a given roll number
def update_marks(file_name, roll_number, new_marks):
try:
with open(file_name, 'rb') as file:
data = pickle.load(file)
found = False
for i, (rn, name, marks) in enumerate(data):
if rn == roll_number:
data[i] = (rn, name, new_marks)
found = True
break
if found:
with open(file_name, 'wb') as file:
pickle.dump(data, file)
print("Marks for roll number", roll_number, "updated to", new_marks)
else:
print("Roll number not found.")
except FileNotFoundError:
print("File not found. Please create the binary file first.")
if __name__ == "__main__":
file_name = "student_data.dat" # You can change the filename if needed
Prepared By:K.Dhanamjay
OUTPUT:
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)
OUTPUT:
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return len(self.items) == 0
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
print("Stack is empty. Cannot pop.") Prepared By:K.Dhanamjay
def peek(self):
if not self.is_empty():
return self.items[-1]
else:
print("Stack is empty. Cannot peek.")
def size(self):
return len(self.items)
stack.push(1)
stack.push(2)
stack.push(3)
OUTPUT:
8. Create a CSV file by entering user-id and password, read and search the password for
given userid
Prepared By:K.Dhanamjay
import csv
# Function to create a CSV file with user IDs and passwords
def create_csv_file(file_name):
data = [] # Initialize an empty list to store user data
if __name__ == "__main__":
file_name = "user_data.csv" # You can change the filename if needed
Prepared By:K.Dhanamjay
OUTPUT:
9. Create a student table and insert data. 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
Prepared By:K.Dhanamjay
-- UPDATE table to modify data
UPDATE Student
SET Gender = 'Male'
WHERE StudentID IN (1, 3, 5);
-- GROUP BY to find the min, max, sum, count, and average of Grade
SELECT
MIN(Grade) AS MinGrade,
MAX(Grade) AS MaxGrade,
SUM(Grade) AS TotalGrade,
COUNT(*) AS TotalStudents,
AVG(Grade) AS AverageGrade
FROM Student;
OUTPUT:
RESULT: The above SQL Queries are executed successfully and it is verified Prepared By:K.Dhanamjay
10. To insert employee data into a MySQL database using the mysql.connector library
import mysql.connector
try:
# Create a connection to the MySQL database
conn = mysql.connector.connect(**db_config)
insert_query = """
INSERT INTO employees (first_name, last_name, email, job_title, salary)
VALUES (%(first_name)s, %(last_name)s, %(email)s, %(job_title)s, %(salary)s)
"""
cursor.execute(insert_query, employee_data)
finally:
# Close the cursor and connection
if cursor: OUTPUT:
cursor.close()
if conn:
conn.close() RESULT: The above python MySQL program executed and verified successfully
Prepared By:K.Dhanamjay