Practical File-1
Practical File-1
Computer Science
PRACTICAL FILE (2023-24)
Submitted by –
1
CERTIFICATE
This is to certify that this Practical file is the bona fide work
under my supervision.
2
INDEX
S. No. Practical Page Sign
Numbers
3
Fetching records using SELECT
2. Consider the following table named 'Exam' with details of marks. Write SQL commands for 13
(i) to (v) and outputs for (vi) to (viii).
(i) To display all information of the students of science in descending order of percentage.
(ii) To display Adno, Name, Percentage, and Stream of those students whose name is less
than 6 characters long.
(iii) To display all students who have 'i' anywhere and 'a' at the last position in their names.
(iv) To display names and streams of students who have got between 85% and 95%.
(v) To display all different class sections.
(vi) SELECT COUNT(*) FROM EXAM;
(vii) SELECT Sname, Percentage FROM EXAM WHERE Name LIKE "N%";
(viii) SELECT ROUND(Percentage, 0) FROM EXAM WHERE Adno = "R005";
(i) Count the number of members of each type for the Gym.
(ii) Display the membership type along with the maximum and minimum fees of
each type.
(iii) Display types of memberships available. Duplicate values should not be
displayed.
(iv) Display total fee given by each gender in Gym.
(v) Display the average age of each gender in Gym.
(vi) Display the sum of fee given in each membership type.
(vii) Display maximum fees given by monthly type members.
(viii) Display minimum fees given by each membership type.
4
Queries Set 4 (Based on DML commands)
4. Consider the following table ‘Gym’. Write SQL commands for (i)to(viii).
18
(i) Display flight number and number of flights from Mumbai from the table
FLIGHTS.
(ii) To display flight number, source, and airlines of those flights where fare is less
than Rs. 10,000.
(iii) Increase the tax by 2% for the flights starting from Delhi.
(iv) Display the flight number and fare to be paid for the flights from Mumbai to
Kochi using the tables FLIGHTS and FARES, where the fare to be paid = fare + fare
* tax / 100.
(v) Display the total number of source stations (eliminating duplicates) present in the
table.
(vi) To count the total number of Indian Airlines flights starting from various cities.
(vii) Display the records of source stations starting with the letter 'B'.
(viii) Display the total number of flights available for each airline.
(ix) Display the fare for the flight from Mumbai to Bangalore.
(x) Display flight number, number of flights, and names of airlines that start from
Delhi.
5
6. Queries Set 6 (Based on Two Tables) 25
Consider the tables given below:
6
Queries and Outputs based on Single-row functions
7. 27
(A) Write SQL commands for the following operations:
a) To display the remainder of 175 and 5.
b) To display the cube of 24.
c) To display the number 563.854741 rounding off to the next hundred.
d) To find the square root of 625.
e) To convert 'welcome' into uppercase and 'FRIENDS' into lowercase.
f) To display 'DIA' from the word "MEDIA".
g) To find the number of characters in "InformaticsPractices".
h) To display the current date and time.
i) To find the name of the weekday on 20th October 2016.
j) To display today's date in DD/MM/YYYY format.
(C) Consider the following MOVIE table and write the SQL queries based on it:
(i) Write a query to display the movie name and movie type.
(ii) Write a query to display the first four digits of the production cost.
(iii) Write a query to display the last four digits of the business cost.
(iv) Write a query to display the weekday of movie release dates.
(v) Write a query to display the day name on which movies are going to be released.
(i) Write a query to display the movie name and movie type.
(ii) Write a query to display the first four digits of the production cost.
(iii) Write a query to display the last four digits of the business cost.
(iv) Write a query to display the weekday of movie release dates.
(v) Write a query to display the day name on which movies are going to be released.
Practical 8
8. 35
Write a menu-driven Python program that defines and uses the following functions:
(i) Function to check whether a number input from the user is a palindrome or not.
(ii) Function to calculate the factorial of a number input from the user.
(iii) Function to check if a number input from the user is prime or not.
(iv) Function to print the Fibonacci series up to a limit 'n' input from the user.
(v) Function to check if a number input from the user is perfect or not.
(vi) Function to check if a number input from the user is Armstrong or not.
7
Practical 9
9. 39
Write a Python program that defines a function to count the number of alphabets and
digits, uppercase letters, lowercase letters, spaces, and other characters in a string
input from the user.
Practical 10
10. 40
Write a Python program that defines a function sin(x, n) to calculate the value of
sin(x) using its Taylor series expansion up to 'n' terms.
Practical 11
11. 41
Write a menu-based Python program that uses functions to perform linear search,
binary search, bubble sort, and insertion sort on a list of numbers.
Practical 12
12. Write a program that generates a series using a function while takes the first and last
44
values of the series and then generates four terms that are equidistant. For example, if
two numbers passed are 1 and 7, then the function returns 1 3 5 7.
Practical 13
13. Write a Python program to display the frequency of each word in a text file.
45
Practical 14
14. Write a Python program that counts the total number of spaces, lines, digits, alphabets
46
and other characters in a given line of text in a text file.
Practical 15
15. Write a Python program to count the total number of words in a text file and to show
47
the word with the maximum length from the text file.
Practical 16
16. Write a program to count the total number of lines in a file and also count the total
48
number of lines starting with ‘H’, ‘R’, and ‘T’.
Practical 17
17. Write a Python program to read the contents of a text file line by line and display each
49
word separated by a $ symbol.
Practical 18
18. Write a Python program to read the contents of a text file and display the total number
50
of consonants, vowels, uppercase characters and lowercase characters present in the
text file.
Practical 19
19. Write a Python program that uses Python’s pickle module to write records (roll
51
number, name, marks) into a binary file ‘student.dat’, also read records from that file
and print them on the screen. The program should perform the following operations
using uder-defined functions:
• search for any roll number and display the corresponding record if found,
otherwise the message “Roll number not found” should be displayed.
• update the marks of the student whose roll number is input from the user.
8
Practical 20
20. Write a Python program to add records in a binary file ‘MARKS.DAT’ with the
55
following fields: rollno, name of student, marks of subject 1, marks of subject 2,
marks of subject 3, and sum of all subjects Read the created binary file
‘MARKS.DAT’ and show the contents of file in the following format:
Practical 21
21. Write a menu-based Python program to add, display, search, modify and delete
57
records in a binary file “emp” using dictionary and functions. Fields of employee file
are : empno : Empolyee number name : Name of Employee salary : Salary of
Employee bonus : 10% of salary
Practical 22
22. Write a Python program to write content for fields - empno, empname, designation
61
and salary to a .CSV file employee.csv. The program should then read the contents
and display them in the form of a list.
Practical 23
23. Write a Python program to read contents of a .CSV file employee.csv (with fields
62
empno, empname, designation and salary) and display them in a tabular form. Also
display the total number of records and sum of salaries of all employees.
Practical 24
24. Write a Python program to search records for given employee name from the CSV file
63
employee.csv containing fields empno, empname, designation and salary
Practical 25
25. Write a menu-based Python program to implement a stack using a list.
64
Practical 26
26. Write a menu-based Python program to implement a stack for maintaining book
67
details like bcode, btitle and price. The program should contain functions to add,
display and delete book details.
Practical 27
27. Write a Python program that uses a stack to check whether a string is a palindrome or
69
not
Practical 28
28. Write a Python program to connect with a MySQL database and store records of
70
employees in a table ‘employee’ created in a database ‘company’. Also, extract
records from the database table and display them
Practical 29
29. Write a MySQL connectivity program in Python to
71
(i) create a database SCHOOL.
(ii) create a table STUDENTS with the specifications - ROLLNO integer,
NAME varchar(20), GENDER character(1), PERCENTAGE decimal in MySQL and
perform the following operations:
a) insert records into the table
b) display the contents of the table
Practical 30
30. Write a program that integrates MySQL with Python to perform the following
73
operations with reference to the table STUDENTS created above:
(i) To sort the records according to names in ascending order.
(ii) To search a student using roll number. If present in the table, update the
record with new name, otherwise display an appropriate error message.
(iii) To search a student using roll number. If present in the table, delete the
record, otherwise display an appropriate error message
9
Practical 1:
Queries Set 1 (Based on DDL commands & DML command INSERT)
Suppose your school management has decided to conduct cricket matches between students of Class
XI and Class XII. Students of each class are asked to join any one of the four teams – Team Titan,
Team Rockers, Team Magnet and Team Hurricane. During summer vacations, various matches will
be conducted between these teams. Help your sports teacher to do the following:
a) Create a database “Sports”.
Ans:
Ans:
Ans:
10
d) Add a new attribute ‘Team_Color’of size 10 characters to the table TEAM.
Ans:
e) Insert these four rows in TEAM table: Row 1: (1, Titan, Red) Row 2: (2, Rockers, Blue) Row 3:
(3, Magnet, Yellow) Row 4: (4, Hurricane, Green)
Ans:
f) Now create another table MATCH_DETAILS and insert data as shown below. Choose
appropriate data types and constraints for each attribute. The attributes ‘FirstTeamID’ and
‘SecondTeamID’ should refer the primary key ‘TeamID’ of the parent table TEAM
Ans:
11
g) Rename the attributes ‘FirstTeamScore’ and ‘SecondTeamScore’ to ‘FTscore’ and ‘STscore’
respectively.
Ans:
12
Practical 2:
Queries Set 2 (Fetching records using SELECT)
Consider the following table named 'Exam' with details of marks. Write SQL commands for (i) to (v)
and outputs for (vi) to (viii).
(i) To display all information of the students of science in descending order of percentage.
Ans:
(ii) To display Adno, Name, Percentage, and Stream of those students whose name is less than 6
characters long.
Ans:
(iii) To display all students who have 'i' anywhere and 'a' at the last position in their names.
Ans:
13
(iv) To display names and streams of students who have got between 85% and 95%.
Ans:
Ans:
Ans:
(vii) SELECT Sname, Percentage FROM EXAM WHERE Name LIKE "N%";
Ans:
Ans:
14
Practical 3:
Queries Set 3 (Based on Aggregate Functions and GROUP BY clause)
Consider the following table ‘Gym’. Write SQL commands for (i) to (viii).
(i) To count the number of members of each type for the Gym.
Ans:
(ii) To display the membership type along with the maximum and minimum fees of each type.
Ans:
15
(iii) To display types of memberships available. Duplicate values should not be displayed.
Ans:
(iv) To display the total fee given by each gender in the Gym.
Ans:
Ans:
Ans:
16
(vii) To display the maximum fees given by monthly type members.
Ans:
Ans:
17
Practical 4:
Queries Set 4 ((Based on DML commands)
Write SQL commands for the following table MOVIE:
Ans:
18
RECORDS INSERTED:
(ii) Display a report listing the movie number, current price, updated price for each movie in the above
table if the price is increased by 15%
Ans:
(iii) Delete all the movies from the table with rating ‘C’.
Ans:
19
(iv) Increase the price of all action movies by 5%. and thriller movies by 1%
Ans:
Ans:
Ans:
20
Practical 5:
Queries Set 5 (Based on Two Tables)
(i) Display flight number & number of flights from Mumbai from the table FLIGHTS.
Ans:
21
(ii) To display flight number, source, airlines of those flights where fare is less than Rs. 10000.
Ans:
(iii) Increase the tax by 2% for the flights starting from Delhi
Ans:
iv) Display the flight number and fare to be paid for the flights from Mumbai to Kochi using the tables
FLIGHTS & FARES, where the fare to be paid = fare + fare * tax / 100
Ans:
(v) Display total number of source stations (eliminated duplicates) present in the table
Ans:
22
(vi) To count total number of IndianAirlines flights starting from various cities
Ans:
(vii) Display the records of source stations starting with the letter 'B'
Ans:
Ans:
(ix) Display the fare for the flight from Mumbai to Bangalore
Ans:
23
(x) Display flight number, number of flights, and names of airlines that start from Delhi:
Ans:
24
Practical 6:
Queries Set 6 (Based on Two Tables)
(i) To display CourseId, TeacherId, Name of Teacher, PhoneNumber of Teachers living in Delhi.
Ans:
(ii) To display the total fees charged by each teacher for the various courses.
Ans:
25
(iii) To display the details of the teacher who charges the lowest fees.
Ans:
(iv) To display TeacherID, Names of Teachers, Subjects of all teachers with names starting with 'S'.
Ans:
(v) To display Subject, CourseID, TeacherID, Teacher Name, and PhoneNumber of teachers whose
fee is more than 5000.
Ans:
26
Practical 7:
Queries and Outputs based on Single-row functions
Ans:
Ans:
Ans:
Ans:
27
e) To convert 'welcome' into uppercase and 'FRIENDS' into lowercase
Ans:
Ans:
Ans:
Ans:
Ans:
28
j) To display today’s date in DD/MM/YYYY format
Ans:
Ans:
Ans:
29
iv. SELECT TRUNCATE(8.975, 2);
Ans:
v. SELECT SIGN(-25);
Ans:
Ans:
Ans:
Ans:
30
ix. SELECT INSTR('UNICODE', 'CO');
Ans:
x. SELECT DAYOFMONTH('2021-06-15');
Ans:
Ans:
Ans:
31
xiii. SELECT MONTHNAME('2021-06-15');
Ans:
Ans:
Ans:
(C) Consider the following MOVIE table and write the SQL queries based on it.
32
(i) Write a query to display the movie name and movie type:
Ans:
(ii) Write a query to display the first four digits of production cost:
Ans:
(iii) Write a query to display the last four digits of business cost:
Ans:
33
(iv) Write a query to display the weekday of movie release dates;
Ans:
(v) Write a query to display the day name on which movies are going to be released:
Ans:
34
Practical 8:
Write a menu-driven Python program that defines and uses the following functions:
(i) Function to check whether a number input from the user is a palindrome or not.
(ii) Function to calculate the factorial of a number input from the user.
(iii) Function to check if a number input from the user is prime or not.
(iv) Function to print the Fibonacci series up to a limit n input from the user.
(v) Function to check if a number input from the user is perfect or not.
(vi) Function to check if a number input from the user is Armstrong or not.
Please note that the program should have a menu-based interface where the user can choose which
function to execute by entering the corresponding option. Each function should perform its specific
task and provide the desired output.
SOURCE CODE:
def palindrome(num):
num2 = int(str(num)[::-1])
if num == num2:
print(num, "is a palindrome.")
else:
print(num, "is not a palindrome.")
def factorial(num):
if num == 0:
return 1
else:
return num*factorial(num - 1)
def prime(num):
for i in range(2,num):
if (num%i) == 0:
return 0
return 1
def fibb(num):
if num<0 or num==0:
print("invalid input")
elif num==1:
print(1)
else:
n1, n2 = 0, 1
print("Fibonacci Series:", n1, n2, end=" ")
for i in range(2, num):
n3 = n1 + n2
n1 = n2
n2 = n3
print(n3, end=" ")
def perfect(num):
a=[]
35
for i in range(1,num):
if num%i==0:
a+=[i]
else:
continue
if sum(a)==num:
print(num,"is a perfect number")
else:
print(num,"is not a perfect number")
def armstrong(num):
numstr=str(num)
n=len(numstr)
sum=0
for i in numstr:
sum+=int(i)**n
if sum==num:
print(num,"is an armstrong number")
else:
print(num,"is not an armstrong number")
#MAIN PROGRAM
while True:
print("\nMenu:")
print("1. Check if a number is a palindrome")
print("2. Calculate the factorial of a number")
print("3. Check if a number is prime")
print("4. Fibonacci series")
print("5. Check if a number is perfect")
print("6. Check if a number is Armstrong")
print("7. Exit")
if choice == 1:
num = int(input("Enter a number: "))
palindrome(num)
elif choice == 2:
num = int(input("Enter a number: "))
fact = factorial(num)
print("Factorial of", num, "is", fact)
elif choice == 3:
num = int(input("Enter a number: "))
x=prime(num)
if x==1:
print(num,"is a prime number")
else:
print(num,"is not a prime number")
elif choice == 4:
num = int(input("Enter the number of terms of the Fibonacci series: "))
fibb(num)
elif choice == 5:
36
num = int(input("Enter a number: "))
perfect(num)
elif choice == 6:
num = int(input("Enter a number: "))
armstrong(num)
elif choice == 7:
print("exiting from the program.....")
break
else:
print("invalid choice")
OUTPUT:
37
38
Practical 9:
Write a Python program that defines a function to count the number of alphabets and digits,
uppercase letters, lowercase letters, spaces, and other characters in a string input from the user.
SOURCE CODE:
def count_char(str):
alphabets = digits = upper = lower = spaces = special = 0
#MAIN PROGRAM
OUTPUT:
39
Practical 10:
Write a Python program that defines a function sin(x, n) to calculate the value of sin(x) using
its Taylor series expansion up to n terms.
SOURCE CODE:
import math
def sin(x,n):
sum=0
for i in range (1,n+1):
a=(-1)**(i+1)
return(sum)
ans=sin(x,n)
OUTPUT :
40
Practical 11:
Write a menu-based Python program that uses functions to perform linear search, binary
search, bubble sort, and insertion sort on a list of numbers.
SOURCE CODE:
def linear_search(lst, n):
for i in range(len(lst)):
if lst[i] == n:
return i
return -1
def bubble_sort(lst):
n = len(lst)
for i in range(n):
for j in range(n-i-1):
if lst[j] > lst[j+1]:
lst[j], lst[j+1] = lst[j+1], lst[j]
def insertion_sort(lst):
for i in range(1, len(lst)):
key = lst[i]
j=i-1
while j >= 0 and lst[j] > key:
lst[j+1] = lst[j]
j -= 1
lst[j+1] = key
#MAIN PROGRAM
while True:
print("Menu:")
print("1. Linear Search")
print("2. Binary Search")
print("3. Bubble Sort")
print("4. Insertion Sort")
print("5. Exit")
c = int(input("Enter your choice: "))
41
if c == 1:
lst=eval(input("Enter the list: "))
n = int(input("Enter the number to search: "))
index = linear_search(lst, n)
if index != -1:
print("Number found at index", index)
else:
print("Number not found")
elif c == 2:
lst=eval(input("Enter the list (sorted): "))
n = int(input("Enter the number to search: "))
index = binary_search(lst, n)
if index != -1:
print("Number found at index", index)
else:
print("Number not found")
elif c == 3:
lst=eval(input("Enter the list: "))
bubble_sort(lst)
print("Sorted array:", lst)
elif c == 4:
lst=eval(input("Enter the list: "))
insertion_sort(lst)
print("Sorted array:", lst)
elif c == 5:
print("Exiting from program ...")
break
else:
print("Invalid choice")
OUTPUT :
42
43
Practical 12:
Write a program that generates a series using a function while takes first and last values of the
series and then generates four terms that are equidistant e.g., if two number passed are 1 and
7, then function returns 1 3 5 7.
SOURCE CODE:
# Main program
first_value = int(input("Enter the first value of the series: "))
last_value = int(input("Enter the last value of the series: "))
OUTPUT:
44
Practical 13:
Write a Python program to display the frequency of each word in a text file
SOURCE CODE:
def count_word_frequency(file_name):
word_frequency = {}
return word_frequency
#MAIN
file_name = input("Enter the name of the file : ")
word_frequency = count_word_frequency(file_name)
print("Word frequency:")
for word, frequency in word_frequency.items():
print(word, “:” ,frequency)
OUTPUT:
45
Practical 14:
Write a Python program that counts the total number of spaces, lines, digits, alphabets and
other characters in a given line of text in a text file.
SOURCE CODE:
def count_char(file_name):
spaces = 0
total_lines = 0
digits = 0
alphabets = 0
other = 0
# MAIN
file_name = input("Enter the name of the file: ")
count_char(file_name)
OUTPUT:
46
Practical 15:
Write a Python program to count the total number of words in a text file and to show the word
with the maximum length from the text file.
SOURCE CODE:
def longestword(file_name):
total_words = 0
longest_word = ""
max_length = 0
# MAIN
file_name = input("Enter the name of the file: ")
longestword(file_name)
OUTPUT:
47
Practical 16:
Write a program to count the total number of lines in a file and also count the total number of
lines starting with ‘H’, ‘R’, and ‘T’
SOURCE CODE:
def count_lines(file_name):
total_lines = 0
H_lines = 0
R_lines = 0
T_lines = 0
# MAIN
file_name = input("Enter the name of the file: ")
count_lines(file_name)
OUTPUT:
48
Practical 17:
Write a Python program to read the contents of a text file line by line and display each word
separated by a $ symbol.
SOURCE CODE:
def symbol(file_name):
with open(file_name, 'r') as file:
for line in file:
words = line.split()
formatted_line = " $ ".join(words)
print(formatted_line)
# MAIN
file_name = input("Enter the name of the file: ")
symbol(file_name)
OUTPUT:
49
Practical 18:
Write a Python program to read the contents of a text file and display the total number of
consonants, vowels, uppercase characters and lowercase characters present in the text file.
SOURCE CODE:
def count_characters(file_name):
vowel = "aeiou"
vowels = 0
consonants = 0
uppercase = 0
lowercase = 0
if char.isupper():
uppercase += 1
else:
lowercase += 1
# MAIN
file_name = input("Enter the name of the file: ")
count_characters(file_name)
OUTPUT:
50
Practical 19:
Write a Python program that uses Python’s pickle module to write records (roll number, name,
marks) into a binary file ‘student.dat’, also read records from that file and print them on the
screen. The program should perform the following operations using uder-defined functions:
(i) search for any roll number and display the corresponding record if found, otherwise the
message “Roll number not found” should be displayed.
(ii) update the marks of the student whose roll number is input from the user.
SOURCE CODE:
import pickle
def read_records(filename):
try:
with open(filename, 'rb') as file:
records = pickle.load(file)
return records
except FileNotFoundError:
return []
while True:
filename = 'student.dat'
records = read_records(filename)
while True:
print("\nOptions:")
print("1. Add a new student record")
print("2. Search for a student record by roll number")
print("3. Update marks of a student by roll number")
print("4. Display all student records")
print("5. Quit")
choice = int(input("Enter your choice: "))
51
if choice == 1:
roll_number = int(input("Enter roll number: "))
name = input("Enter name: ")
marks = float(input("Enter marks: "))
records.append({'roll_number': roll_number, 'name': name, 'marks': marks})
write_records(filename, records)
elif choice == 2:
roll_number = int(input("Enter roll number to search: "))
record = search_record(roll_number, records)
if record:
print("Student Record:")
print(f"Roll Number: {record['roll_number']}")
print(f"Name: {record['name']}")
print(f"Marks: {record['marks']}")
else:
print("Roll number not found.")
elif choice == 3:
roll_number = int(input("Enter roll number to update marks: "))
new_marks = float(input("Enter new marks: "))
if update_marks(roll_number, new_marks, records):
write_records(filename, records)
print("Marks updated successfully.")
else:
print("Roll number not found.")
elif choice == 4:
print("Student Records:")
for record in records:
print(f"Roll Number: {record['roll_number']}")
print(f"Name: {record['name']}")
print(f"Marks: {record['marks']}")
elif choice == 5:
break
else:
print("Invalid choice. Please try again.")
52
OUTPUT:
53
54
Practical 20:
Write a Python program to add records in a binary file ‘MARKS.DAT’ with the following fields:
rollno, name of student, marks of subject 1, marks of subject 2, marks of subject 3, and sum of
all subjects Read the created binary file ‘MARKS.DAT’ and show the contents of file in the
following format:
Roll No. Name Total Marks
SOURCE CODE:
import pickle
def read_records(filename):
try:
records = []
with open(filename, 'rb') as file:
while True:
try:
record = pickle.load(file)
records.append(record)
except EOFError:
break
return records
except FileNotFoundError:
return []
def display_records(records):
if not records:
print("No records found.")
return
# MAIN
filename = marks.DAT'
while True:
choice = input("Do you want to add a record? (yes/no): ")
if choice != 'yes':
break
55
rollno = int(input("Enter Roll No: "))
name = input("Enter Name: ")
marks = [int(x) for x in input("Enter marks for subjects (comma-separated): ").split(',')]
records = read_records(filename)
display_records(records)
OUTPUT:
56
Practical 21:
.Write a menu-based Python program to add, display, search, modify and delete records in a
binary file “emp” using dictionary and functions. Fields of employee file are :
empno : Empolyee number
name : Name of Employee
salary : Salary of Employee
bonus : 10% of salary.
SOURCE CODE:
import pickle
import os
try:
with open('emp', 'ab') as file:
pickle.dump(record, file)
print("Record added successfully.")
except FileNotFoundError:
with open('emp', 'wb') as file:
pickle.dump(record, file)
print("File created, record added.")
except EOFError:
break
if not found:
print("Record not found.")
except FileNotFoundError:
print("File 'emp' not found or empty.")
os.remove('emp')
os.rename(temp_file, 'emp')
except FileNotFoundError:
print("File 'emp' not found or empty.")
# Menu function
def menu():
while True:
print("\nEmployee Records Management")
print("1. Add Record")
print("2. Display Records")
print("3. Search Record")
print("4. Delete Record")
print("5. Exit")
if choice == '1':
58
add_record()
elif choice == '2':
display_records()
elif choice == '3':
search_record()
elif choice == '4':
delete_record()
elif choice == '5':
print("Exiting program...")
break
else:
print("Invalid choice. Please enter a number between 1 and 5.")
menu()
OUTPUT:
59
60
Practical 22:
Write a Python program to write content for fields - empno, empname, designation and salary - to
a .CSV file employee.csv. The program should then read the contents and display them in the
form of a list.
SOURCE CODE:
import csv
OUTPUT:
61
Practical 23:
Write a Python program to read contents of a .CSV file employee.csv (with fields
empno, empname, designation and salary) and display them in a tabular form. Also
display the total number of records and sum of salaries of all employees.
SOURCE CODE:
:
import csv
total_records = 0
total_salary = 0
for i in reader:
print(i[0], i[1], i[2], i[3])
total_records += 1
total_salary += int(i[3])
OUTPUT:
62
Practical 24:
Write a Python program to search records for given employee name from the CSV file
employee.csv containing fields empno, empname, designation and salary.
SOURCE CODE:
import csv
found_records = []
next(reader)
return found_records
file_name = 'employee.csv'
employee_name = input("Enter employee name to search: ")
if records:
print(f"Found {len(records)} record(s) for '{employee_name}':")
for record in records:
print(record)
else:
print(f"No records found for '{employee_name}'")
OUTPUT:
63
Practical 25:
Write a menu-based Python program to implement a stack using a list.
SOURCE CODE:
def pop(stack):
if not stack:
return "Stack is empty"
return stack.pop()
def peek(stack):
if not stack:
return "Stack is empty"
return stack[-1]
def display(stack):
if not stack:
print("Stack is empty")
else:
print("Stack Contents:")
for item in reversed(stack):
print(item)
stack = []
while True:
print("\nStack Operations:")
print("1. Push")
print("2. Pop")
print("3. Peek")
print("4. Display")
print("5. Exit")
if choice == '1':
item = input("Enter item to push: ")
push(stack, item)
elif choice == '2':
popped_item = pop(stack)
print(f"Popped item: {popped_item}")
elif choice == '3':
peeked_item = peek(stack)
print(f"Peeked item: {peeked_item}")
elif choice == '4':
display(stack)
elif choice == '5':
64
print("Exiting the program...")
break
else:
print("Invalid choice. Please enter a valid option.")
OUTPUT:
65
66
Practical 26:
Write a menu-based Python program to implement a stack for maintaining book details like bcode,
btitle and price. The program should contain functions to add, display and delete book details..
SOURCE CODE:
def add_book(stack):
bcode = input("Enter Book Code: ")
btitle = input("Enter Book Title: ")
price = float(input("Enter Price: "))
book = (bcode, btitle, price)
stack.append(book)
print("Book details added to the stack.")
def delete_book(stack):
if stack:
deleted_book = stack.pop()
print(f"Deleted book details: {deleted_book}")
else:
print("Stack is empty")
def display_books(stack):
if stack:
print("Book Details in Stack:")
for book in reversed(stack):
bcode, btitle, price = book
print(f"Book Code: {bcode}, Title: {btitle}, Price: {price}")
else:
print("Stack is empty")
stack = []
while True:
print("\nBook Management System:")
print("1. Add Book")
print("2. Delete Book")
print("3. Display Books")
print("4. Exit")
if choice == '1':
add_book(stack)
elif choice == '2':
delete_book(stack)
elif choice == '3':
display_books(stack)
elif choice == '4':
print("Exiting the program...")
break
else:
print("Invalid choice. Please enter a valid option.")
67
OUTPUT:
68
Practical 27:
Write a Python program that uses a stack to check whether a string is a palindrome or not
SOURCE CODE:
def palindrome(s):
s = s.lower()
stack = []
for char in s:
stack.append(char)
reversed_s = ""
while stack:
reversed_s += stack.pop()
if s == reversed_s:
print(s,"is a palindrome")
else:
print(s,"is not a palindrome")
while True:
s=input("enter the string : ")
palindrome(s)
OUTPUT:
69
Practical 28:
Write a Python program to connect with a MySQL database and store records of employees in a
table ‘employee’ created in a database ‘company’. Also, extract records from the database table
and display them.
SOURCE CODE:
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="root",
passwd="",
database="company"
)
mycursor = mydb.cursor()
mycursor.executemany(sql, val)
mydb.commit()
mycursor.close()
mydb.close()
OUTPUT:
70
Practical 29:
Write a MySQL connectivity program in Python to
(i) create a database SCHOOL.
(ii) create a table STUDENTS with the specifications - ROLLNO integer, NAME varchar(20),
GENDER character(1), PERCENTAGE decimal in MySQL and perform the following
operations:
a) insert records into the table
b) display the contents of the table
SOURCE CODE:
import mysql.connector
import mysql.connector
conn = mysql.connector.connect(host="localhost", user="root", passwd='', database="Schooll")
mycur = conn.cursor()
records = mycur.fetchall()
print("Student Records:")
if not records:
71
print("No records found.")
else:
for record in records:
print(record)
mycur.close()
OUTPUT:
72
Practical 30:
Write a program that integrates MySQL with Python to perform the following operations with
reference to the table STUDENTS created above:
(i) To sort the records according to names in ascending order.
(ii) To search a student using roll number. If present in the table, update the record with new
name, otherwise display an appropriate error message.
(iii) To search a student using roll number. If present in the table, delete the record, otherwise
display an appropriate error message
SOURCE CODE:
import mysql.connector
def sort_records_by_name(cursor):
sort_query = 'SELECT * FROM STUDENTS ORDER BY NAME ASC'
cursor.execute(sort_query)
return cursor.fetchall()
elif c==2:
roll_to_delete = input("Enter the ROLLNO of the student to delete: ")
73
if search_student_by_roll_and_delete(mycur, roll_to_delete):
print(f"Record with ROLLNO {roll_to_delete} deleted successfully.")
conn.commit()
else:
print(f"No record found with ROLLNO {roll_to_delete}. Delete failed.")
elif c==3:
roll_to_update = input("Enter the ROLLNO of the student to update name: ")
new_name = input("Enter the new NAME for the student: ")
else:
print("Invalid Choice")
mycur.close()
conn.close()
OUTPUT:
74