0% found this document useful (0 votes)
26 views11 pages

9 CS Questions

Cs nadu
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)
26 views11 pages

9 CS Questions

Cs nadu
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/ 11

QST-1 : Read a text file line by line and display each word separated by

a#

Solution :

fh=open(r"myfile.txt","r")
item=[]
a=""
while True:

a=fh.readline()

words=a.split()
for j in words:
item.append(j)
if a =="":
break
print("#".join(item))

QST -2 : Read a text file and display the number of


vowels/consonants/uppercase/loweгсasе characters in the file.

Solution :

def count_characters(file_path):

vowels = "aeiouAEIOU"

consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"

uppercase_count = 0

lowercase_count = 0

vowel_count = 0

consonant_count = 0

try:

with open(file_path, 'r') as file:

content = file.read()

for char in content:


if char.isalpha():

if char.isupper():

uppercase_count += 1

elif char.islower():

lowercase_count += 1

if char in vowels:

vowel_count += 1

elif char in consonants:

consonant_count += 1

print(f"Uppercase characters: {uppercase_count}")

print(f"Lowercase characters: {lowercase_count}")

print(f"Vowels: {vowel_count}")

print(f"Consonants: {consonant_count}")

except FileNotFoundError:

print(f"File '{file_path}' not found.")

except Exception as e:

print(f"An error occurred: {e}")

QST -3 : Remove all the lines that contain`a' in a file and write it to
another file.

Solution :

fo=open("hp.txt","w")

fo.write("Harry Potter")

fo.write("There is a difference in all harry potter books\nWe can see it as harry


grows\nthe books were written by J.K rowling ")

fo.close()
fo=open('hp.txt','r')

fi=open('writehp.txt','w')

l=fo.readlines()

for i in l:

if 'a' in i:

i=i.replace('a','')

fi.write(i)

fi.close()

fo.close()

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

Solution :

import pickle

def create_file(name, roll_number):

with open('students.bin', 'ab') as file:

pickle.dump((name, roll_number), file)

def search_roll_number(roll_number):

with open('students.bin', 'rb') as file:

while True:

try:

name, number = pickle.load(file)

if number == roll_number:

return name
except EOFError:

break

return None

# Create some data

create_file('John Doe', 1)

create_file('Jane Doe', 2)

# Search for a roll number

name = search_roll_number(1)

if name is not None:

print(f'Name: {name}')

else:

print('Roll number not found.')

QST – 5 : Create a binary file with roll number, name and marks. Input a roll
number and update the marks.

Solution :

class Stack:

def __init__(self):

self.items = []

def is_empty(self):

return len(self.items) == 0

def push(self, item):

self.items.append(item)

print(f"Pushed: {item}")

def pop(self):
if not self.is_empty():

popped_item = self.items.pop()

print(f"Popped: {popped_item}")

return popped_item

else:

print("Stack is empty. Cannot pop.")

def display(self):

if not self.is_empty():

print("Stack Contents:")

for item in reversed(self.items):

print(item)

else:

print("Stack is empty.")

# Example usage

stack = Stack()

stack.push(10)

stack.push(20)

stack.push(30)

stack.display()

stack.pop()

stack.pop()

stack.display()
QST – 6 : Write a random number generator that generates random numbers
between 1 and 6 (simulates a dice).

Solution :

import math.random

def generate_random_number():

return random.randint(1, 6)

print(generate_random_number())

QST – 7 : Write a Python program to implement a stack using list.


Solution :

class Stack:

def __init__(self):

self.stack = []

def push(self, item):

self.stack.append(item)

def pop(self):

if len(self.stack) == 0:

return None

else:

return self.stack.pop()

def peek(self):
if len(self.stack) == 0:

return None

else:

return self.stack[-1]

def is_empty(self):

return len(self.stack) == 0

QST- 8 : Create a CSV file by entering user-id and password, read and search
the password for given userid.

Solution :
import csv

def create_csv():

# Open the CSV file in write mode

with open('user_passwords.csv', 'w', newline='') as file:

writer = csv.writer(file)

writer.writerow(["user_id", "password"])

# Get user-id and password from the user

while True:

user_id = input("Enter user-id (or 'quit' to stop): ")

if user_id.lower() == 'quit':

break

password = input("Enter password: ")

writer.writerow([user_id, password])

def search_password(user_id):
# Open the CSV file in read mode

with open('user_passwords.csv', 'r') as file:

reader = csv.reader(file)

next(reader) # Skip the header row

# Search for the password of the given user-id

for row in reader:

if row[0] == user_id:

return row[1]

return None # Return None if no user-id is found

# Create the CSV file

create_csv()

# Search for a password

user_id = input("Enter user-id to search for: ")

password = search_password(user_id)

if password is not None:

print(f"The password for user-id {user_id} is {password}")

else:

print(f"No user-id {user_id} found")

QST – 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
Solution :

-- Create a student table

CREATE TABLE IF NOT EXISTS student (

student_id INT PRIMARY KEY,

first_name VARCHAR(50) NOT NULL,

last_name VARCHAR(50) NOT NULL,

age INT,

marks INT

);

-- Insert data into the student table

INSERT INTO student (student_id, first_name, last_name, age, marks)

VALUES

(1, 'John', 'Doe', 18, 85),

(2, 'Jane', 'Smith', 19, 92),

(3, 'Alice', 'Johnson', 20, 78),

(4, 'Bob', 'Williams', 18, 95);

-- Display the student table

SELECT * FROM student;

-- ALTER table to add a new attribute

ALTER TABLE student

ADD COLUMN email VARCHAR(100);


-- ALTER table to modify data type

ALTER TABLE student

MODIFY COLUMN age VARCHAR(3);

-- ALTER table to drop an attribute

ALTER TABLE student

DROP COLUMN marks;

-- UPDATE table to modify data

UPDATE student

SET age = 21

WHERE student_id = 3;

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

SELECT * FROM student

ORDER BY age ASC;

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

SELECT * FROM student

ORDER BY marks DESC;

-- DELETE to remove a tuple

DELETE FROM student


WHERE student_id = 2;

-- GROUP BY and find the min, max, sum, count, and average

SELECT

MIN(age) AS min_age,

MAX(age) AS max_age,

SUM(age) AS total_age,

COUNT(*) AS total_students,

AVG(age) AS avg_age

FROM student;

You might also like