Computer Science Record Notebook Programs (4th May 2025)
Computer Science Record Notebook Programs (4th May 2025)
AIM: Write a python program to Read a text file line by line and display
each word separated by a #.
ALGORITHM::
PROGRAM:
def process_text_file(file_path):
result = ""
try:
with open(file_path, 'r') as file:
for line in file:
words = line.split()
line_result = ""
except FileNotFoundError:
print("File not found")
return
print(result)
file_path = "sample.txt"
process_text_file(file_path)
=================================================
INPUT
Hello world
This is a sample text file
Read and display words
Separated by #
OUTPUT
Hello#world
This#is#a#sample#text#file
Read#and#display#words
Separated#by#
====================================================
2.
AIM: Write a python program to Read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file.
ALGORITHM:
PROGRAM:
def count_characters_in_file(file_path):
vowels = consonants = uppercase = lowercase = 0
try:
with open(file_path, 'r') as file:
content = file.read()
for char in content:
if char.isalpha():
if char.lower() in "aeiou":
vowels += 1
else:
consonants += 1
if char.isupper():
uppercase += 1
if char.islower():
lowercase += 1
except FileNotFoundError:
print("File not found")
return
print("Vowels:", vowels)
print("Consonants:", consonants)
print("Uppercase characters:", uppercase)
print("Lowercase characters:", lowercase)
file_path = "sample.txt"
count_characters_in_file(file_path)
==========================
INPUT
Hello World!
This is a Sample Text File with 123 numbers.
The quick brown fox jumps over the lazy dog.
OUTPUT
Vowels: 45
Consonants: 70
Uppercase characters: 20
Lowercase characters: 95
================================================
3. AIM: Write a python program to remove all the lines that contain the
character 'a' in a file and write it to another file.
ALGORITHM:
1. Open the source file for reading.
2. Open the destination file for writing.
3. Read the source file line by line in a loop.
4. Check if the line contains the character 'a'. If it does not, write it to the
destination file.
5. Close the source and destination files.
PROGRAM:
except FileNotFoundError:
print("File not found")
return
INPUT
This is a sample text.
It contains several lines.
Some of these lines have the letter 'a'.
Others do not.
We are removing lines with 'a'.
OUTPUT
Others do not.
=================================================
4. AIM: Write a python program to 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.
ALGORITHM:
# Function to search for a given roll number and display the name
except FileNotFoundError:
print("File not found")
if __name__ == "__main__":
file_name = "student_data.txt"
records = [("Alice", 101), ("Bob", 102), ("Charlie", 103), ("David", 104)]
create_binary_file(file_name, records)
search_roll = 103
search_and_display_name(file_name, search_roll)
RESULT: The above program has been executed sucessfully.
====================================================
INPUT
The program is set to search for the roll number 103.
OUTPUT
Name: Charlie, Roll Number: 103
5. AIM: Write a python program to Create a binary file with roll number, name
and marks. Input a roll number and update the marks.
ALGORITHM:
1. Start
2. Define file_name = "student_data.csv"
3. Define initial records as list of lists:
[[101,"Alice",90], [102,"Bob",85], [103,"Charlie",88], [104,"David",92]]
4. Define search_roll = 103 and new_marks = 95
6. Update Marks:
a. Open file_name in read mode
b. Read all records into a temporary list
c. For each record:
i. If roll number matches search_roll:
- Update marks to new_marks
ii. Add record to updated list
d. Open file_name in write mode
e. Write all updated records back to file
f. Close file
7. Display Records:
a. Open file_name in read mode
b. For each row in file:
i. Print roll number, name, and marks
c. Close file
8. End
program:
import csv
# Main program
file_name = "student_data.csv"
records = [[101, "Alice", 90], [102, "Bob", 85], [103, "Charlie", 88], [104, "David",
92]]
search_roll = 103
new_marks = 95
create_file(file_name, records)
update_marks(file_name, search_roll, new_marks)
display_records(file_name)
=======================================================
INPUT
The program is set to update the marks for roll number 103 to
95.
OUTPUT
Roll number not found
Marks for Charlie have been updated to 95
Roll number not found
==================================
6. AIM: Write a python program for a random number generator that generates
random numbers between 1 and 6 (simulates a dice).
ALGORITHM:
PROGRAM:
import random
def roll_dice():
random_number = random.randint(1, 6)
return random_number
# Main program
while True:
random_number = roll_dice()
print("You rolled:", random_number)
again = input("Roll again? (y/n): ")
if again.lower() != 'y':
print("Goodbye!")
break
============================
INPUT
There is no specific input required for this program.
OUTPUT
You rolled: 3 # The number may vary as it's random
7. AIM: Write a python program for creating a CSV file by entering user-id and
password, reading and searching for the password for a given user-id
ALGORITHM:
PROGRAM:
import csv
# Function to create a CSV file with user-id and password
def create_csv_file(file_name, user_data):
with open(file_name, 'w', newline='') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(["User-ID", "Password"])
for user_id, password in user_data:
writer.writerow([user_id, password])
# Main program
if __name__ == "__main__":
file_name = "user_data.csv"
user_data = [("user1", "password1"), ("user2", "password2"), ("user3",
"password3")]
create_csv_file(file_name, user_data)
search_user_id = "user2"
password = search_password(file_name, search_user_id)
=========================
INPUT
The program is set to search for the password associated with the
user-id "user2."
OUTPUT
======================================================
ALGORITHM:
1. Initialize
o Empty list stack and variable top = None.
2. Menu Loop
o Show options: Push, Pop, Peek, Display, Exit.
o Take user input.
3. Operations
o Push: Add item to stack, update top.
o Pop: Remove last item if stack not empty, else "Underflow".
o Peek: Return last item if exists, else "Underflow".
o Display: Print stack top to bottom.
o Exit: Stop the program.
PROGRAM:
def isEmpty(stk):
if stk == []:
return True
else:
return False
def Push(stk,item):
stk.append(item)
top = len(stk) - 1
def Pop(stk):
if isEmpty(stk):
return "UnderFlow"
else:
item = stk.pop()
if len(stk) == 0:
top = None
else:
top = len(stk) - 1
return item
def Peek(stk):
if isEmpty(stk):
return "underflow"
else:
top = len(stk) -1
return stk[top]
def Display(stk):
if isEmpty(stk):
print("Stack Empty")
else:
top = len(stk) -1
print(stk[top],"<--top")
for a in range(top -1 , -1 ,-1):
print(stk[a])
Stack = []
top = None
while True:
print("STACK OPERATIONS")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display Stack")
print("5. Exit")
s
Output:
==========================================
ALGORITHM:
PROGRAM:
def factorial(n):
if n == 0 or n == 1:
return 1
else:
return n * factorial(n - 1)
===============================================
INPUT
The program is set to calculate the factorial of n = 5
OUTPUT
The factorial of 5 is 120
==================================================
Algorithm:
def is_palindrome(s):
# Base case: If the string is empty or has only one character, it's a palindrome
if len(s) <= 1:
return True
# Recursive case: Check if the first and last characters are the same
if s[0] == s[-1]:
return is_palindrome(s[1:-1])
else:
return False
if __name__ == "__main__":
input_str = "racecar" # Input value to check if it's a palindrome
if is_palindrome(input_str):
print(f"{input_str} is a palindrome")
else:
print(f"{input_str} is not a palindrome")
=================================
INPUT
The program is set to check if the string "racecar" is a palindrome
OUTPUT
racecar is a palindrome
=============================================
11. Aim : Write a program to search an element in a list and display the
frequency of element present in list and their location using Linear search.
Algorithm:
1. Start
2. Initialize variables:
3. arr: The input list to search in.
4. target: The element to search for in the list.
5. count: Initialize a variable to keep track of the frequency of the element
(set to 0).
6. locations: Initialize an empty list to store the indices where the element is
found.
7. For each element at index i in the list arr: a. If arr[i] is equal to target: i.
Increment count by 1. ii. Append i to the locations list.
8. If count is greater than 0: a. Print "Element target was found count times
in the list." b. Print "Locations of target in the list: locations."
9. Otherwise, if count is 0: a. Print "Element not found in the list."
10. End
Program:
for i in range(len(arr)):
if arr[i] == target:
count += 1
locations.append(i)
# Input values
input_list = [3, 5, 2, 6, 8, 3, 4, 3, 9]
element_to_search = 3
# Output
print("Element {element_to_search} was found " , frequency , " times in the
list.")
if frequency > 0:
print("Locations of {element_to_search} in the list: " , locations)
else:
print("Element not found in the list.")
================================================
Input :
Input values: 3
input_list: The list in which you want to search for an element.
element_to_search: The element you want to search for in the list.
Output: :
Element 3 was found 3 times in the list.
Locations of 3 in the list: [0, 5, 7]
============================================
12. Aim: Write a program to pass list to a function and double the odd values
and half even values of a list and display list element after changing
Algorithm:
1. Start
2. Initialize variables:
3. input_list: The list of numbers to be processed.
4. output_list: An empty list to store the modified values.
5. Create a function modify_list that accepts a list as a parameter.
a. Initialize an empty list result to store the modified values.
b. For each element num in the input list:
6. If num is odd (num % 2 != 0), double it and append to result.
7. If num is even (num % 2 == 0), halve it and append to result.
8. Return the result list.
9. Call the modify_list function with input_list as the argument and store the
result in output_list.
10. Display the modified list output_list.
11. End
Program :
def modify_list(input_list):
result = []
for num in input_list:
if num % 2 != 0: # Odd number
result.append(num * 2)
else:
result.append(num // 2) # Even number (integer division)
return result
# Input values
input_list = [2, 5, 8, 11, 14, 17]
========================
Output: :
Modified List: [1, 10, 4, 22, 7, 34]
Algorithm:
1. Start
2. Input a number n from the user.
3. Validate Input:
o If n is not a valid integer, display an error message and Stop.
4. Check if n is less than 2:
o If true, n is not prime. Display "Not a Prime Number" and Stop.
5. Loop from i = 2 to i <= square root of n:
o If n is divisible by i (i.e., n % i == 0):
n is not prime. Display "Not a Prime Number" and Stop.
6. If loop completes without finding a divisor:
o n is prime. Display "Prime Number".
7. Stop
Program :
def is_prime(n):
# Numbers less than 2 are not prime
if n < 2:
return False
# Check for divisibility from 2 to square root of n
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
# Main program
try:
num = int(input("Enter a number to check: "))
if is_prime(num):
print(num , " is a Prime Number")
else:
print( num , " is not a Prime Number")
except ValueError:
print("Please enter a valid integer!")
Result:The above program has been executed sucessfully.
======================
================================================
14. Aim: Write a program to pass a string to a function and count how many
vowels are present in the string.
Algorithm:
1. Start
2. Initialize a variable vowel_count to 0 to keep track of the count of vowels.
3. Input a string from the user and store it in a variable input_string.
4. Create a function count_vowels that accepts a string as a parameter:
a. Initialize vowel_count to 0 within the function.
b. For each character char in the string: i. Convert char to lowercase to
ensure case-insensitive matching. ii. Check if char is a vowel ('a' or
'A') using if and elif statements. iii. If char is a vowel, increment
vowel_count by 1.
c. Return vowel_count.
5. Call the count_vowels function with the input_string as the argument and
store the result in vowel_count.
6. Display the count of vowels in the string.
7. End
Program :
def count_vowels(input_string):
vowel_count = 0
for char in input_string:
char_lower = char.lower()
if char_lower == 'a':
vowel_count += 1
elif char_lower == 'e':
vowel_count += 1
elif char_lower == 'i':
vowel_count += 1
elif char_lower == 'o':
vowel_count += 1
elif char_lower == 'u':
vowel_count += 1
return vowel_count
=============================
Input : :
Output: :
Number of vowels in the string: 8
A
AB
ABC
ABCD
AB C D E
Algorithm:
1. Start
2. Input the number of rows n for the pyramid pattern from the user.
3. Create a loop that iterates from 1 to n to represent the current row:
a. Create an inner loop that iterates from 1 to the current row number:
i. Inside the inner loop, calculate and print the corresponding
alphabet character. You can use the chr() function to convert a
number to its corresponding character.
b. Move to the next line to start a new row.
4. End
Program :
============================
Input : :
The user is prompted to enter the number of rows for the pyramid pattern (e.g.,
5).
Output: :
A
AB
ABC
ABCD
ABCDE
16 Aim : To create two tables for stationary and consumer and execute the
given commands using SQL.
TABLE:STATIONARY
TABLE: CONSUMER
iii) To display the ConsumerName , Address from table Consumer and Company
and Price from table Stationery with their corresponding matching S_ID .
iv) To increase the Price of all Stationary by 2.
OUTPUT:
Company
ABC
XYZ
CAM
17. AIM: To create two tables for item and traders and execute the given
commands using SQL.
TABLE:ITEM
TABLE:TRADERS
i) To display the details of all the items in ascending order of item names (i.e
IName)
ii) To display item name and price of all those items, whose price is in the range
of 10000 and 22000 (both values inclusive)
iii) To display the number of items , which are traded by each trader. The
expected output of this query should be
T01 2
T02 2
T03 1
iv) To display the Price , item name(i.e IName) and quantity(i.e Qty) of those
items which have quantity more than 150.
v) To display the names of those traders, who are either from DELHI or from
MUMBAI.
CREATE TABLE ITEM(Code int , IName char(25) , Qty int , Price int , Company
char(25), TCode char(5));
=============================================
OUTPUT:
ii) select IName , Price from ITEM where Price between 10000 and 22000;
IName Price
DIGITAL PAD 121 11000
Tcode Count(*)
T01 2
T02 2
T03 1
TName
ELECTRONICS SALES
BUSY STORE CORP
===================================================
18. AIM: To create two tables for doctor and salary and execute the given
commands using SQL.
TABLE:DOCTOR
TABLE: SALARY
i) Display NAME of all doctors who are in “MEDICINE” having more than 10
years experience from table DOCTOR
ii) Display the average salary of all doctors working in “ENT” department using
the tables DOCTOR and SALARY. (Salary=BASIC+ALLOWANCE)
iii) Display minimum ALLOWANCE of female doctors.
iv) Display DOCTOR.ID , NAME from the table DOCTOR and BASIC , ALLOWANCE
from the table SALARY with their corresponding matching ID.
CREATE TABLE DOCTOR(ID int NOT NULL PRIMARY KEY, NAME char(25) , DEPT
char(25) , SEX char , EXPERIENCE int);
CREATE TABLE SALARY(ID int, BASIC int, ALLOWANCE int, CONSULTATION int);
==========================================
OUTPUT:
NAME
Bill
ii) select avg(BASIC+ALLOWANCE) “avg salary” from DOCTOR , SALARY where
DOCTOR.ID=SALARY.ID and DEPT=”ENT”;
Avg salary
13000.00
min(ALLOWANCE)
1700
DEPT
ENT
ORTHOPEDIC
CARDIOLOGY
SKIN
MEDICINE
================================================
19 . AIM: To create two tables for company and customer and execute the given
commands using SQL.
TABLE : COMPANY
TABLE : CUSTOMER
1. To display those company name which are having price less than 30000.
2. To display the name of the companies in reverse alphabetical order.
3. To increase the price 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
5. To display the details of company where productname as mobile.
RESULT:
Thus the given program executed successfully.
=================================
OUTPUT: :
NAME
NEHA SONI
NAME
SONY
ONIDA
NOKIA
DELL
BLACKBERRY
3. update customer set price = price + 1000 where name like ‘s%’;
===============================================
20. AIM: To create table for teacher and execute the given commands using SQL.
TABLE : TEACHER
==============================
Name
Shriya
3. select Name , Dateofjoin from teacher order by Dateofjoin asc;
Name Dateofjoin
Santhosh 12/12/96
Jishnu 10/01/97
Shakthi 25/02/97
Shiva 27/02/97
Shriya 31/07/97
Ragu 05/09/97
Sharmila 24/03/98
Shanmathi 01/07/99
count(*)
3
Department count(*)
Computer 2
History 3
Maths 3
21. AIM: To integrate SQL with Python by importing the MySQL module and
extracting data from result set
PROGRAM:
import mysql.connector as sqltor
mycon.close( )
=====================
OUTPUT:
PROGRAM:
OUTPUT:
23. AIM: Integrate SQL with Python by importing the MySQL module to search
an employee using eno , if it is present in table display the record
PROGRAM:
import mysql.connector as mc
mycon=mc.connect(host='localhost',user='root',password='root1',
database='db12')
if mycon.is_connected( ):
print("Py->Sql connected")
eno=int(input("Enter num:"))
mcursor=mycon.cursor( )
mcursor.execute("select * from emp")
allrow=mcursor.fetchall( )
OUTPUT:
Py->Sql connected
Enter num : 103
(103,’Cinu , 43, ‘Namakkal’)
=================================================
24. AIM: To integrate SQL with Python by importing the MySQL module to
search a student using rollno and delete the record.
PROGRAM :
import mysql.connector as mc
mycon=mc.connect(host='localhost',user='root',password='root1',
database='db12')
if mycon.is_connected():
print("Py->Sql connected")
eno=int(input("Enter num:"))
mcursor=mycon.cursor()
mcursor.execute("select * from emp")
allrow=mcursor.fetchall()
for row in allrow:
if row[0]==eno:
mcursor.execute("delete from emp where eno={}".format(eno))
mcursor.execute("select * from emp")
print(mcursor.fetchall())
mycon.commit()
mycon.close()
RESULT:
Thus the given is program executed successfully.
======================
OUTPUT:
Py -> sql is connected Enter num : 102 (101,’Anu’,23,’Salem’)
(103,’Cinu’,43,’Namakkal’)
(104, ‘Nishanth’, 46,’Chennai’)
(105, ‘Nanda’, 56, ‘Erode’)