Document 1
Document 1
1. Write a function COUNTWORDS (), to count the number of words in each line of a text file
“POEM.TXT”
Answer:
def COUNTWORDS(file):
string = file.read()
w=string.split()
print("number of words:",len(w))
file = open("Q1\POEM.txt","r")
COUNTWORDS(file)
Output:
2. Write a function SNAME (), to create a text file “names.txt” and search for a name.
Answer:
def SNAME(file):
for i in range(num):
file.write(nam+" ")
file.close()
file = open('Q2/names.txt',"r")
st=file.read()
w-string.split()
Found = False
for i in w:
if i == s:
Found = False
break
if Found == True:
print("name is found")
else:
file.close()
file = open('Q2/names.txt',"w")
SNAME(file)
Output:
3. Write a function COPYTEXT () to create a text file “story.txt” copy all sentences starting with
‘t‘into a new file “temp.txt” and print it.
Answer:
def COPYTEXT():
sentences_with_t = []
sentences = file.readlines()
if sentence.strip().lower().startswith('t'):
sentences_with_t.append(sentence.strip())
temp_file.write(sentence + "\n")
print(sentence)
COPYTEXT()
OUTPUT:
4. Write a function COPYB (), to copy all word starting with ‘b’ into a new file.
ANSWER:
def COPYB():
b_words = []
words = line.split()
if word.lower().startswith('b'):
b_words.append(word.strip('.,!?"\''))
b_file.write(word + "\n")
print(word)
COPYB()
OUTPUT:
5. Write a function HESHE (), to count the number of times the word ‘he’ or ‘she’ appears in
story.txt
Answer:
def HESHE():
content = file.read()
he_count = content.lower().count("he")
she_count = content.lower().count("she")
total_count = he_count + she_count
HESHE()
Output:
6. Write a function PALIN (),to search and print all palindrome words from story.txt.
Answer:
def PALIN():
content = file.read()
words = content.split()
palindromes = []
cleaned_word = word.strip('.,!?"\'').lower()
palindromes.append(cleaned_word)
print(palindrome)
PALIN()
Content:
Output:
7. Write a function LINE ()to read a text file line by line and display each word separated by
a#
Answer:
def LINE():
words = line.split()
formatted_line = "#".join(words)
print(formatted_line)
LINE()
Content:
Output:
8. Write a function CHARACTER (), to read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file.
Answer:
def CHARACTER():
vowels = "aeiouAEIOU"
consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"
vowel_count = 0
consonant_count = 0
uppercase_count = 0
lowercase_count = 0
content = file.read()
for char in content:
if char.isalpha():
if char in vowels:
vowel_count += 1
consonant_count += 1
if char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1
CHARACTER()
Content:
Output:
9. Write a function REMOVEA (),to remove all the lines that starts with the character 'a' in a file
and write it to another file.
Answer:
def REMOVEA():
lines = file.readlines()
new_file.write(line)
print("Lines starting with 'a' have been removed and saved to 'filtered_story.txt'.")
REMOVEA()
Content(after execution)
Output:
10. Write a function DISPLAYWORDS() in Python to read lines from a text file “POEM.TXT”
and display those words which are less than 4 characters.
Answer:
def DISPLAYWORDS():
content = file.readlines()
short_words = []
words = line.split()
if len(word) < 4:
short_words.append(word)
print(word)
DISPLAYWORDS()
Content:
Output:
11. Write a function to create a CSV file by entering user-id and password, read and search the
password for given user id.
Answer:
import csv
def create_user_csv():
writer = csv.writer(file)
while True:
if user_id.lower() == 'exit':
break
writer.writerow([user_id, password])
def search_password():
found = False
if row[0] == user_id_to_search:
found = True
break
if not found:
def main():
create_user_csv()
search_password()
main()
Content:
Output:
Searching for network.
12.. Create a csv file with fields bno, name, type, and price. Write a menu driven program using
functions:
2. To existing book.csv if type is fiction increase price by 20, update the file
Answer:
import csv
import os
def create_csv():
if not os.path.exists("book.csv"):
writer = csv.writer(file)
else:
writer = csv.writer(file)
def increase_price_fiction():
updated_rows = []
reader = csv.reader(file)
header = next(reader)
updated_rows.append(header)
if row[2].lower() == "fiction":
updated_rows.append(row)
writer = csv.writer(file)
writer.writerows(updated_rows)
print("Prices updated for fiction books.")
def display_file():
reader = csv.reader(file)
print("Records in 'book.csv':")
print(row)
def count_comedy_books():
comedy_count = 0
reader = csv.reader(file)
if row[2].lower() == "comedy":
comedy_count += 1
def delete_record():
updated_rows = []
found = False
reader = csv.reader(file)
header = next(reader)
updated_rows.append(header)
if row[0] != bno_to_delete:
updated_rows.append(row)
else:
found = True
writer = csv.writer(file)
writer.writerows(updated_rows)
if found:
else:
def main_menu():
while True:
print("\nMenu:")
print("6. Exit")
if choice == '1':
add_data()
increase_price_fiction()
display_file()
count_comedy_books()
delete_record()
break
else:
main_menu()
Output:
If i chose:
1.
2.
3.
4.
5.
6.
13. Create a CSV file called stud.csv with fields sno,sname,stream and marks.Write a function
csvcopy(), to copy the contents of stud.csv to class.csv.
Answer:
import csv
import os
def create_stud_csv():
if not os.path.exists("stud.csv"):
writer = csv.writer(file)
# Sample data
def csvcopy():
reader = csv.reader(source_file)
with open("class.csv", "w", newline='') as dest_file:
writer = csv.writer(dest_file)
writer.writerow(row)
def main():
if __name__ == "__main__":
main()
Content:
Output;
14. Create a binary file emp.dat which have n dictionaries with fields ecode, ename, designation
and salary. Write a menu driven program using functions for:
1. appending
2. displaying
Answer:
import pickle
import os
def create_emp_file():
if not os.path.exists("emp.dat"):
def append_employee():
employee = {}
pickle.dump(employee, file)
def display_employees():
print("Employee Records:")
try:
while True:
employee = pickle.load(file)
print(employee)
except EOFError:
pass
def search_employee():
found = False
try:
while True:
employee = pickle.load(file)
if employee['ecode'] == ecode_to_search:
found = True
break
except EOFError:
if not found:
def update_salary():
try:
while True:
pos = file.tell()
employee = pickle.load(file)
if employee['designation'].lower() == 'manager':
employee['salary'] += 500
employee['salary'] += 200
pickle.dump(employee, file)
except EOFError:
def main_menu():
create_emp_file()
while True:
print("\nMenu:")
print("5. Exit")
if choice == '1':
append_employee()
search_employee()
update_salary()
break
else:
if __name__ == "__main__":
main_menu()
OUTPUT:
If i chose:
1.
2.
3.
4.
5.
15. Write a function to make a new file with only managers and print name of manager with
highest salary.
Answer;
import pickle
import os
def create_manager_file():
managers = []
try:
while True:
employee = pickle.load(file)
if employee['designation'].lower() == 'manager':
managers.append(employee)
except EOFError:
pass
pickle.dump(manager, file)
if managers:
else:
def main():
create_manager_file()
if __name__ == "__main__":
main()
Emp.dat contains:
Output becomes to be;
16. Write a function to insert a new record assuming details are in ascending order of ecode:
2. Display it
3. Sort it
Answer;
import pickle
import os
def create_employee_file():
employees = [
pickle.dump(employee, file)
def display_employees():
print("Employee Records:")
try:
while True:
employee = pickle.load(file)
print(employee)
except EOFError:
pass
def insert_employee(new_employee):
employees = []
try:
while True:
employee = pickle.load(file)
employees.append(employee)
except EOFError:
pass
employees.append(new_employee)
employees.sort(key=lambda x: x['ecode'])
pickle.dump(employee, file)
def main():
create_employee_file()
display_employees()
insert_employee(new_employee)
display_employees()
if __name__ == "__main__":
main()
import pickle
import os
def create_employee_file():
employees = [
pickle.dump(employee, file)
def display_employees():
print("Employee Records:")
try:
while True:
employee = pickle.load(file)
print(employee)
except EOFError:
pass
def insert_employee(new_employee):
employees = []
try:
while True:
employee = pickle.load(file)
employees.append(employee)
except EOFError:
pass
employees.append(new_employee)
employees.sort(key=lambda x: x['ecode'])
pickle.dump(employee, file)
def main():
create_employee_file()
display_employees()
insert_employee(new_employee)
display_employees()
if __name__ == "__main__":
main()
Output:
17.Write a random number generator that generates random numbers between 1 and 6 (simulates
a dice).
Answer:
import random
def roll_dice():
return random.randint(1, 6)
def main():
for _ in range(number_of_rolls):
if __name__ == "__main__":
main()
Ouput:
18.
Answer:
1.
2.
19. Consider the following tables SCHOOL and answer this question :
Answer:
1.
2.
3.
4.
20.
Answer:
1.
2.
3.
4.
21. Consider the following tables Supplier and Consumer. Write SQL commands for the
statements (a) to (d).
(a) To display the C_ID, Supplier name, Supplier Address, Consumer Name and Consumer
Address for every Consumer
Answer:
1.
2.
3.
4.
22. Write the outputs of the SQL queries (i) to (iv) based on the relations Drink and Consumer
given below:
Answer:
1.
2
3.
4.
23. Write SQL commands for the queries (i) to (iv) based on a table COMPANY
andCUSTOMER
1. To display those company name which are having prize less than 30000.
3. To increase the prize by 1000 for those customer whose name starts with ‘S’?
4. To add one more column totalprice with decimal(10,2) to the table customer
Answer:
1.
2.
3.
4.
24. Write a menu driven program using functions to implement all the stack operations?
Answer:
stack = []
def push():
stack.append(student)
def pop():
if not stack:
else:
student = stack.pop()
def peek():
if not stack:
print("Stack is empty.\n")
else:
student = stack[-1]
def display():
if not stack:
print("Stack is empty.\n")
else:
print("Stack contents:")
print(student)
print()
def menu():
while True:
if choice == 1:
push()
elif choice == 2:
pop()
elif choice == 3:
peek()
elif choice == 4:
display()
elif choice == 5:
break
else:
print("Invalid choice.\n")
if __name__ == "__main__":
menu()
Output:
25. Vignesh has created a dictionary “employee” with employee name as key and their salary as
values. Write a program to perform the following operations in Python: (a) Push the names of
those employees into a stack where the salary is less than 50000 (b) Pop the elements of the stack
and display those names.
Answer:
Output:
26. Harsha has created a list 'mylist' of 10 integers. You have to help him to create a stack by
performing the following functions in Python: (a) Traverse each element of the list and push all
those numbers into the stack which are divisible by 3. (b) Pop from the stack and display all the
content
Answer:
Output:
27.. Write Python connectivity program to
· Code
· Address
· Commission
· Salary
Answer:
import sqlite3
conn = sqlite3.connect('SALES.db')
cursor = conn.cursor()
def create_table():
SalesManName TEXT,
Address TEXT,
Commission REAL,
Salary REAL)''')
conn.commit()
def retrieve_data():
rows = cursor.fetchall()
print(row)
print()
def delete_records():
conn.commit()
def insert_data():
data = [
conn.commit()
def menu():
create_table()
insert_data()
retrieve_data()
Output:
28. Write a menu driven program to demonstrate four major operations using my SQL
connectivity
· Add
· Update
· delete
· display
Answer:
import mysql.connector
conn = mysql.connector.connect(
cursor = conn.cursor()
def create_table():
name VARCHAR(100),
marks FLOAT,
city VARCHAR(100),
age INT)''')
conn.commit()
def add_student():
Output :
29. 29. Write a program to demonstrate fetchone(), fetchall(), fetchmany()and rowcount using
SQL connectivity .Create a table TEACHERS (ID,NAME,SUBJECT,CLASS)
Answer:
Output:
30. A public school is Managing Student data in STUDENT table in SCHOOL database, write a
python code that connects to database school and retrieves . all records and displays total number
of students
Answer:
import mysql.connector
conn = mysql.connector.connect(
cursor = conn.cursor()
# Function to retrieve all student records and display the total number of students
def retrieve_students():
print("Student Records:")
retrieve_students()
cursor.close()
conn.close()
import mysql.connector
conn = mysql.connector.connect(
cursor = conn.cursor()
# Function to retrieve all student records and display the total number of students
def retrieve_students():
print("Student Records:")
print(student)
retrieve_students()
cursor.close()
conn.close()
Output: