0% found this document useful (0 votes)
93 views10 pages

Computer Science-CLASS-12-RECORD PROGRAMS

The document contains 9 Python programs that perform various tasks related to working with files and databases: 1. A program that reads a text file and separates each word with a # symbol. 2. A program that reads a text file and counts the vowels, consonants, uppercase and lowercase characters. 3. A program that removes all lines containing the letter 'a' from a file and writes the output to a new file. 4. Programs for creating, searching, and updating a binary file containing student name, roll number, and marks. 5. A random number generator program that simulates rolling a dice. 6. A program that implements a stack using a Python list
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)
93 views10 pages

Computer Science-CLASS-12-RECORD PROGRAMS

The document contains 9 Python programs that perform various tasks related to working with files and databases: 1. A program that reads a text file and separates each word with a # symbol. 2. A program that reads a text file and counts the vowels, consonants, uppercase and lowercase characters. 3. A program that removes all lines containing the letter 'a' from a file and writes the output to a new file. 4. Programs for creating, searching, and updating a binary file containing student name, roll number, and marks. 5. A random number generator program that simulates rolling a dice. 6. A program that implements a stack using a Python list
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/ 10

Computer Science (083) Record Programs: Prepared By: K.

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:

RESULT: The above python program successfully executed and it is verified

2. Read a text file and display the number of vowels/consonants/uppercase/lowercase


characters in the file.
# 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:
text = file.read()

# 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

This is a Sample Text File.


We are testing the Python code.
Display characters Count.

OUTPUT:

RESULT: The above python program successfully executed and it is verified


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

# Input and output file paths


input_file_path = "input.txt" # Replace with your input file path
output_file_path = "output.txt" # Replace with your output file path

# 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)

# Print a message to confirm the operation


print("Lines with 'a' removed and saved to", output_file_path)

input.txt

This is a sample line without 'a'.


Here's a line with 'a'.
Another line without 'a'.

OUTPUT:

Output.txt

This is a sample line without 'a'.


Another line without 'a'.

RESULT: The above python program successfully executed and it is verified

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

# Get user input for records


while True:
name = input("Enter name (or type 'exit' to finish): ")
if name == 'exit':
break
roll_number = input("Enter roll number: ")
data.append((name, roll_number))

# 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 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:

RESULT: The above python program successfully executed and it is verified

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

create_binary_file(file_name) # Create the binary file


# Input the roll number and new marks to update
roll_number_to_update = input("Enter roll number to update marks: ")
new_marks = input("Enter new marks: ")
update_marks(file_name, roll_number_to_update, new_marks)

Prepared By:K.Dhanamjay
OUTPUT:

RESULT: The above python program successfully executed and it is verified

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)

# Roll the dice


result = roll_dice()
print("You rolled a", result)

OUTPUT:

RESULT: The above python program successfully executed and it is verified

7. Write a Python program to implement a stack using list

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 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)

# Example usage of the stack


if __name__ == "__main__":
stack = Stack()

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

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

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


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

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

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


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

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

OUTPUT:

RESULT: The above python program successfully executed and it is verified.

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

# Get user input for user IDs and passwords


while True:
user_id = input("Enter User ID (or type 'exit' to finish): ")
if user_id == 'exit':
break
password = input("Enter password: ")
data.append([user_id, password])

# Write the data to the CSV file


with open(file_name, 'w', newline='') as file:
csv_writer = csv.writer(file)
csv_writer.writerows(data)
print("Data saved to", file_name)

# Function to search for a password given a user ID


def search_password(file_name, user_id):
try:
with open(file_name, 'r') as file:
csv_reader = csv.reader(file)
for row in csv_reader:
if row[0] == user_id:
print("User ID:", user_id)
print("Password:", row[1])
return
print("User ID not found.")
except FileNotFoundError:
print("File not found. Please create the CSV file first.")

if __name__ == "__main__":
file_name = "user_data.csv" # You can change the filename if needed

create_csv_file(file_name) # Create the CSV file

# Input the user ID to search for the password


user_id_to_search = input("Enter User ID to search for the password: ")
search_password(file_name, user_id_to_search)

Prepared By:K.Dhanamjay
OUTPUT:

RESULT: The above python program successfully executed and it is verified.

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

-- Create the student table


CREATE TABLE Student (
StudentID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Age INT,
Grade FLOAT
);

-- Insert data into the student table


INSERT INTO Student (StudentID, FirstName, LastName, Age, Grade)
VALUES
(1, 'John', 'Doe', 20, 85.5),
(2, 'Jane', 'Smith', 21, 92.0),
(3, 'David', 'Johnson', 19, 78.5),
(4, 'Emily', 'Williams', 22, 94.5),
(5, 'Michael', 'Brown', 20, 89.0);

-- ALTER table to add a new attribute


ALTER TABLE Student
ADD Gender VARCHAR(10);

Prepared By:K.Dhanamjay
-- UPDATE table to modify data
UPDATE Student
SET Gender = 'Male'
WHERE StudentID IN (1, 3, 5);

-- ORDER BY to display data in ascending order of Grade


SELECT * FROM Student
ORDER BY Grade;

-- ORDER BY to display data in descending order of Age


SELECT * FROM Student
ORDER BY Age DESC;

-- DELETE to remove a tuple with a specific StudentID


DELETE FROM Student
WHERE StudentID = 4;

-- 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

# Replace these with your database credentials


db_config = {
"host": "localhost",
"user": "your_username",
"password": "your_password",
"database": "your_database_name"
}

try:
# Create a connection to the MySQL database
conn = mysql.connector.connect(**db_config)

# Create a cursor object to execute SQL commands


cursor = conn.cursor()

# Insert employee data into the database


employee_data = {
"first_name": "John",
"last_name": "Doe",
"email": "john@example.com",
"job_title": "Software Engineer",
"salary": 75000
}

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)

# Commit the changes to the database


conn.commit()

print("Employee data inserted successfully.")

except mysql.connector.Error as error:


print("Error: {}".format(error))

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

You might also like