The Following document
contains all the computer
programs done during the
year 2022-23
Computer
SciencePractical record
Asad Shaikh
No. Date Programs Remarks
1
2
3
4
5
6
7
Program 1 Date:
Menu Driven Program
Aim:
Write a menu driven program using functions to find:
Factorial of a number
Check the number is even or odd
Reverse the number
Check weather the number is palindrome or not
Check whether the number is Armstrong or not
Procedure:
# Modules used in the program
import time
import math
# FUNCTIONS used in the program are created below
# Factorial
def fact(num):
return(math.factorial(num))
# Odd or Even
def eo(num):
if num % 2 == 0:
print("> The number is EVEN")
else:
print("> The number is ODD")
# Sum of Digits
def sum_digits(num):
sum = 0
for digit in str(num):
sum += int(digit)
return sum
# Reversing the Digits
def reverse(num):
global revr_num
if (num > 0):
Reminder = num % 10
revr_num = (revr_num * 10) + Reminder
reverse(num // 10)
return revr_num
# Palindrome checker
def palindrome(num):
temp = num
rev = 0
while (num>0):
dig = num % 10
rev = rev * 10 + dig
num = num // 10
if (temp == rev):
print("> YES the number is a Palindrome.")
else:
print("> NO the number is not a Palindrome.")
# Armstrong Checker
def armstrong(num):
m = len(str(num))
temp = num
add_sum = 0
while temp!= 0:
k = temp % 10
add_sum += k**m
temp = temp // 10
if add_sum == number:
print("> It is an Armstrong Number")
else:
print("> It is not an Armstrong NUmber")
print("="*40)
print("M E N U P R O G R A M".center(40))
print("="*40)
for i in range(6):
print("\nSelect a command from the following options.")
time.sleep(.5)
print("1. Find factorial of a number")
time.sleep(.5)
print("2. Odd or even checker")
time.sleep(.5)
print("3. Find the sum of digits")
time.sleep(.5)
print("4. Reversing the number")
time.sleep(.5)
print("5. Palindrome checker")
time.sleep(.5)
print("6. Amstrong checker")
time.sleep(.5)
work = int(input("\nEnter an option to perform tasks: "))
# Factorial finder
if work == 1:
print("-"*20)
number = int(input("Enter the Number: "))
factorial = fact(number)
print("> Factorial of", number, "is", factorial)
print("-"*20)
# Odd or even Checker
elif work == 2:
print("-"*20)
number = int(input("Enter the Number: "))
even_or_odd = eo(number)
print("-"*20)
# Sum of the Digits
elif work == 3:
print("-"*20)
number = int(input("Enter the Number: "))
sum_digits(number)
print("> The sum of the digits are: ",sum_digits(number))
print("-"*20)
# Reversing the digits
elif work == 4:
print("-"*20)
number = int(input("Enter the number: "))
revr_num = 0
rev_num = reverse(number)
print("> Reverse of entered number is = %d" % revr_num)
print("-"*20)
# Palindrome Checker
elif work == 5:
print("-"*20)
number = int(input("Enter the Number: "))
palindrome(number)
print("-"*20)
# Armstrong Checker
elif work == 6:
print("-"*20)
number = int(input("Enter the Number: "))
armstrong(number)
print("-"*20)
else:
print("The mentioned command is out of range.\n"
"Please try again!")
Output:
Result:
The program is executed
successfully and the output is
verified.
Program 2: Date:
Menu Driven - lists
Aim:
Write a program using functions to input a list of numbers and find:
i. Sum of elements in the list
ii. Sum of elements at odd positions
iii. Sum of elements at even positions
Procedure:
def sum_all(l: list):
print("-"*40)
S = 0
for i in l:
S+=i
print("Sum of all elements of list: ",S)
print("-"*40)
def sum_odd(l: list):
print("-"*40)
S = 0
if len(l) < 2:
return "Enter more than 1 element to use this command"
for i in range(1,len(l),2):
S+=l[i]
print("Sum of all the elemets at ODD POSITIONS: ",S)
print("-"*40)
def sum_even(l: list):
print("-"*40)
S = 0
for i in range(0,len(l),2):
S+=l[i]
print("Sum of all the elements at EVEN POSITIONS: ",S)
print("-" * 40)
def main():
print("="*60)
print("M E N U D R I V E N P R O G R A M W I T H L I S T".
center(40))
print("="*60)
input_taken = False
run = True
while run:
if not input_taken:
l_elements = list(map(float, input("Enter all the elements with a
space: ").split()))
input_taken = True
print("\n\t1. Sum of elements\n"
"\t2. Sum of elements at odd positions\n"
"\t3. Sum of elemts at even positions\n"
"\t4. Create a new list\n")
command = int(input("Enter a command: "))
print()
if command == 1:
print(sum_all(l_elements))
elif command == 2:
print(sum_odd(l_elements))
elif command == 3:
print(sum_even(l_elements))
elif command == 4:
input_taken = False
continue
Conti = input("Do you want to continue? (y/n): ")
if Conti != "y":
run = False
if __name__ == '__main__':
main()
Output:
Result:
The program is executed successfully and the output is verified.
Program 3 Date:
Check the Existence of the word
Aim:
Write a program to input a sentence and a word, and check whether the word
exists in the
sentence or not. If yes, find the number of occurrences of the word in the
sentence.
Procedure:
def word_count(word_to_count, word_list):
return f"{word_to_count} had been repeated
{word_list.count(word_to_count)} times."
def main():
print("="*40)
print("W O R D F I N D E R".center(40))
print("="*40)
run = 'y'
while run == 'y':
print()
sentence = input("\tEnter a sentence: ")
word_list = sentence.split()
word = input("Enter the word you want to find: ")
if word in word_list:
print(word_count(word, word_list))
else:
print("Word not Found!")
run = input("\nDo you want to continue (y/n): ")
if __name__ == '__main__':
main()
Output:
Result:
The program is executed successfully and the output is verified.
Program 4 Date:
Manipulating Text File
Aim:
Write a menu driven program to manipulate a text file. Add the following
options:
i. Input some contents into a file.
ii. Output the contents from the file.
iii. Count and display number of vowels, consonants, lowercase and uppercase
characters in the file.
Procedure:
# Entering Data in to the File
def write_data():
Main_File = open("SampleTxt.txt", "a")
data = input("Enter your Data: ")
Main_File.write(data)
Main_File.close()
print("\tData Added ✔")
# Add Data
def AddData(Data):
with open('SampleTxt.txt', 'a') as File:
File.write(Data)
File.close()
# Modify the Existing data
def mod_data(check):
with open('SampleTxt.txt','r') as File:
for i in File.readlines():
Line = i
X = i.split('Book No:')[1]
Y = i.split('|')[0]
if check in Y:
return True
File.close()
# Reading Data in the File
def read_data():
Main_File = open("SampleTxt.txt", "r")
data = Main_File.read()
print(data)
Main_File.close()
# Displaying total characters in the file
def display_char():
Main_File = open("SampleTxt.txt", "r")
data = Main_File.readlines()
str = ' '.join(data)
print(f" Character count: {len(str)}\n\n"
f" File Content: {str}")
Main_File.close()
# Displaying total words in the File
def Total_Words():
Main_file = open("SampleTxt.txt", "r")
data = Main_file.readlines()
str = ' '.join(data)
print(f" Word Count: {len(str.split(' '))}\n\n"
f" File Content: {str}")
Main_file.close()
# Counting Vowels and Consonants in the File
def TotalVowelsCon():
with open('SampleTxt.txt', 'r') as File:
Data = File.readlines()
Str = ' '.join(Data)
Vowels = ['a','e','i','o','u']
CountVowels = 0
CountConsonants = 0
for i in Str:
if i in Vowels:
CountVowels += 1
else:
CountConsonants += 1
print(f'Vowels: {CountVowels}\n'
f'Consonants: {CountConsonants}\n\n'
f'File Content: {Str}')
File.close()
'''def istoupcount():
with open('SampleTxt.txt', 'r') as File:
Data = File.readlines()
str = ' '.join(Data)'''
# Entering the string as a Record
def writing_string_as_record():
file = open('SampleTxt.txt', 'a')
bno = int(input("Enter the Book number: "))
bname = input("Enter the Book name: ")
author = input("Enter the Author name: ")
price = int(input("Enter the Book price: "))
Brec = str(bno) + "," + bname + "," + author + "," + str(price) + "\n"
file.write(Brec)
file.close()
# Removing records
def remove_data(line):
with open('SampleTxt.txt', 'w') as File:
with open('SampleTxt.txt', 'r') as File:
for i in File.readlines():
line = i
X = i.split('Book No:')[1]
Y = i.split('|')[0]
if check in Y:
line.replace(f'{line}','')
File.close()
# Main Loop
def main():
while True:
print("="*30)
print("TEXT FILE MANAGEMENT".center(30))
print("="*30)
print("\t 1 ➜ Create/Open and Enter Data")
print("\t 2 ➜ Read Existing Data")
print("\t 3 ➜ Display total characters in file")
print("\t 4 ➜ Display total words in the file")
print("\t 5 ➜ Display total vowels and consonants in file")
print("\t 6 ➜ Entering String as a record")
print("\t 7 ➜ Modify Data in the File")
command = int(input("\n\t Enter your desired command: "))
if command == 1:
print("\n-----Entering Write Mode-----")
write_data()
print("-----Write Mode Closed-----\n")
elif command == 2:
print("\n-----Entering Read Mode-----")
print("➜ Showing all Data ")
read_data()
print("-----Read Mode Closed----\n")
elif command == 3:
print("\n-----Character Count-----")
display_char()
print("------------------------\n")
elif command == 4:
print("\n-----Total Words-----")
Total_Words()
print("--------------------\n")
elif command == 5:
print("\n-----Total Vowels and Consonants-----")
TotalVowelsCon()
print("------------------------------------\n")
elif command == 6:
print("\n-----String as Records-----")
print("1. Entering String as a Record")
strcmd = int(input("Select from the above options: "))
if strcmd == 1:
writing_string_as_record()
print("-----------------------\n")
else:
print("---INVALID COMMAND---")
break
elif command == 7:
check = input('Book Number you would like to Modify: ')
if mod_data(check) == True:
print('\n📚 Book Exists. Please Enter Details of Modified Book
below 👇🏻\n')
BookN = int(input('Enter Book Number: '))
Name = input('Enter Book Name: ')
Author = input('Enter Author Name: ')
Price = int(input('Enter Price: '))
Data = f'Book No: {BookN} | Name: {Name} | Author: {Author} |
Price {Price}\n'
remove_data(BookN)
AddData(Data)
print('\nData Modified ✔')
else:
ReTry = input("Do you want to Try Again? (yes/no): ")
if ReTry.lower() == "yes" or "Yes":
continue
else:
break
if __name__ == '__main__':
main()
Output:
Program 5 Date:
Binary File Management
Aim:
Write a menu driven program to create a binary file and add the following
information into it.
a. Roll Number
b. Student name
c. Grade and Division
Also add menus to do the following:
i. Search for a student using his roll number
ii. Display all students in the file
iii. Modify the details of a students
iv. Delete a student from the file
Procedure:
import pickle
import os
def insert_rec():
with open("p5.dat", "ab") as f:
c = 'y'
while True:
print("\n-----Adding New Student-----")
roll = int(input("Enter Student Roll Number: "))
name = input("Enter Student Name: ")
grade = input("Enter Student Grade & Division: ")
d = {"Roll": roll, "Name": name, "grade": grade}
pickle.dump(d, f)
print("---Record Inserted---")
print("Want to insert more records (y/n)")
c = input("> ")
c = c.lower()
if c not in 'y':
break
f.close()
main_menu()
def display_rec():
f = open("p5.dat", "rb")
print("\n-----Displaying all Records-----")
try:
while True:
d = pickle.load(f)
print(d)
except Exception:
f.close()
main_menu()
def search_rec():
f = open("p5.dat", "rb")
print("\n------Searching Student------")
s = int(input("Enter Roll Number to search: "))
f1 = 0
try:
while True:
d = pickle.load(f)
if d["Roll"] == s:
f1 = 1
print(d)
break
except Exception:
f.close()
if f1 == 0:
print("-----Record not Found-----\n")
else:
print("------Record Found------\n")
main_menu()
def update_rec():
f1 = open("p5.dat", "rb")
f2 = open("temp.dat", "wb")
print("\n------Updating Record------")
s = int(input("Enter Roll Number to update: "))
try:
while True:
d = pickle.load(f1)
if d["Roll"] == s:
d["Name"] = input("Enter Name: ")
d["grade"] = input("Enter grade: ")
pickle.dump(d, f2)
except EOFError:
print("-----Record Updated-----\n")
f1.close()
f2.close()
os.remove("p5.dat")
os.rename("temp.dat", "p5.dat")
main_menu()
def delete_rec():
f1 = open("p5.dat", "rb")
f2 = open("temp.dat", "wb")
print("\n------Deleting Record------")
s = int(input("Enter Roll Number to delete: "))
try:
while True:
d = pickle.load(f1)
if d["Roll"] != s:
pickle.dump(d, f2)
except EOFError:
print("-----Record Deleted-----\n")
f1.close()
f2.close()
os.remove("p5.dat")
os.rename("temp.dat", "p5.dat")
main_menu()
def main_menu():
print("\n=====Binary Student Management======")
print("\t1. Insert a record")
print("\t2. Search a record")
print("\t3. Update a record")
print("\t4. Display all records")
print("\t5. Delete a record")
print("\t6. Exit")
choice = int(input("Enter your choice: "))
if choice == 1:
insert_rec()
elif choice == 2:
search_rec()
elif choice == 3:
update_rec()
elif choice == 4:
display_rec()
elif choice == 5:
delete_rec()
elif choice == 6:
print("Thank You")
quit()
else:
print("Invalid Command, Please Try Again!")
if __name__ == '__main__':
main_menu()
Output:
Result:
The program is executed successfully, and Output is verified.
Program 6 Date:
Data File Handling
Aim:
Write a program to read the contents of a text file line by line and write all the
lines into another file except those line starting with ‘a’ or ‘A’.
Procedure:
with open ("D:\Python Projects\File Handling\MF", "r") as f:
f1 = open("MFtemp.txt", 'w')
read = f.read()
for i in read:
if i != 'a' and i != 'A':
f1.write(i)
f1.close()
Output:
Result:
The program is executed successfully, and the output is verified.
SQL 1 Date:
SQL Table 1
Aim:
Creating Teacher and Salary table as follows:
TEACHER
ID NAME DEPT SEX EXPERIENCE
1111 SANDYA MATHS FEMALE 10
1212 MANU COMPUTER MALE 3
1265 KRISHNA SCIENCE MALE 1
1321 AKHILA BIOLOGY FEMALE 5
1801 TARUN HINDI MALE 8
Teacher table contains the following constrains:
ID INT, NAME CHAR(10), DEPT CHAR(10), SEX CHAR(6),EXPERIENCE INT
SALARY
ID BASIC ALLOWANCE
1310 3500 5000
1321 3500 5000
1212 300 2000
1801 340 2500
1111 350 2560
Salary table contains the following constrains:
ID INT, BASIC DECIMAL(8,2), ALLOWANCE DECIMAL(8,2)
Procedure:
Syntax:
i. Display ID and Name of all the teachers
ii. Display the details of all the teachers in ascending order of their name
iii. Display the details of all the teachers with more than 5 years of
experience.
iv. Display the ID, Name and total salary of all teachers.
v. Display the ID, Name and basic salary of all the teachers.
vi. Display the allowance of all the female teachers.
vii. Increase the allowance of all the male teachers by 200% of their basic
salary.
viii. Increase the allowance of all the female teachers with 10 years of
experience by 225% of their basic salary.
ix. Delete the record of Tarun.
x. Add a new column named SCHOOL in teacher table and update the
school’s name of all teachers to “Al Ain Juniors”
Program 15 Date:
MYSQL Program 2
Aim:
Create an account table and an transact table as follows with the following
constraints:
Account: ANO INT, ANAME CHAR (10), ADDRESS CHAR (20)
Transact : TRNO CHAR(5), ANO INT, AMOUNT CHAR(8,2), TYPE CHAR(10), DOT
DATE)
Procedure:
Syntax:
i. Display the details of all transactions of type deposit from table transact.
ii. Display ano and amount of all deposits and withdrawals done in the
month of October 2017 from transact table.
iii. Display the last date of transaction from the table transact for the
accounts having ANO as 103.
iv. Display all ANO and ANAME and DOT of those persons from tables
account and transact who have done transaction less than to equal to
3000.
v. Display the ANO and ANAME of all customers who are not from Chennai
or Hyderabad.
vi. Display the number of customers from each city.
vii. Display the amount deposited and withdrawn from the table transact.
viii. Update the name of ‘Ali Reza’ to ‘Ali Raza’.
ix. Display the ano, aname, trno, amount and type from the tables account
and transact where the transaction has done on ‘2017-10-22’.
x. Delete the records of T005 from transact.