Computer Science
Computer Science
Submitted By Submitted To
Sriansh Shukla Tr. ___________________
XII A1
Python Programming
1. Read a text file line by line and display each word separated by a
`#`.
PYTHON
def display_words_with_hash(filename):
with open(filename, 'r') as file:
for line in file:
words = line.split()
print('#'.join(words))
display_words_with_hash('sample.txt')
2. Read a text file and display the number of
vowels/consonants/uppercase/lowercase characters.
PYTHON
def count_characters(filename):
vowels = "aeiouAEIOU"
vowel_count = consonant_count = uppercase_count =
lowercase_count = 0
count_characters('sample.txt')
3. Remove all the lines that contain the character 'a' in a file and
write it to another file.
PYTHON
def remove_lines_with_a(input_file, output_file):
with open(input_file, 'r') as infile, open(output_file,
'w') as outfile:
for line in infile:
if 'a' not in line:
outfile.write(line)
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.
PYTHON
import pickle
PYTHON
def update_marks(filename, roll_number, new_marks):
with open(filename, 'rb') as file:
students = pickle.load(file)
PYTHON
import random
def roll_dice():
return random.randint(1, 6)
PYTHON
class Stack:
def __init__(self):
self.stack = []
def pop(self):
return self.stack.pop() if not self.is_empty() else None
def peek(self):
return self.stack[-1] if not self.is_empty() else None
def is_empty(self):
return len(self.stack) == 0
def size(self):
return len(self.stack)
s = Stack()
s.push(1)
s.push(2)
print(s.pop()) # Outputs: 2
8. Create a CSV file by entering user-id and password, read, and
search the password for the given user-id.
PYTHON
import csv
def create_csv(filename):
with open(filename, mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['User ID', 'Password'])
writer.writerow(['user1', 'pass1'])
writer.writerow(['user2', 'pass2'])
create_csv('users.csv')
search_password('users.csv', 'user1')
Database Management Tasks
SQL
CREATE TABLE student (
roll_no INT PRIMARY KEY,
name VARCHAR(100),
marks INT
);
SQL
SELECT * FROM student ORDER BY marks ASC;
SELECT * FROM student ORDER BY marks DESC;
5. DELETE to remove tuple(s).
SQL
DELETE FROM student WHERE roll no = 102;
6. GROUP BY and find the min, max, sum, count, and average.
SQL
SELECT COUNT(*) FROM student;
SELECT AVG(marks) FROM student;
SELECT MAX(marks) FROM student;
SELECT MIN(marks) FROM student;
SELECT SUM(marks) FROM student;
conn = sqlite3.connect('students.db')
cursor = conn.cursor()
cursor.execute('''
CREATE TABLE IF NOT EXISTS student (
roll_no INTEGER PRIMARY KEY,
name TEXT NOT NULL,
marks INTEGER NOT NULL
)
''')
conn.close()