0% found this document useful (0 votes)
48 views

Practical File-1

The document outlines a practical file for a computer science class. It includes instructions to create databases and tables to store information about school cricket teams and matches. It also provides examples of SQL queries to retrieve and manipulate data, including using aggregation, functions, and multiple tables.

Uploaded by

Renu Kumari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
48 views

Practical File-1

The document outlines a practical file for a computer science class. It includes instructions to create databases and tables to store information about school cricket teams and matches. It also provides examples of SQL queries to retrieve and manipulate data, including using aggregation, functions, and multiple tables.

Uploaded by

Renu Kumari
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

NEW ERA PUBLIC SCHOOL DWARKA

Computer Science
PRACTICAL FILE (2023-24)

Submitted by –

Name : Ishant Sharma

Class : XII Section : Science

Roll No. : __________

1
CERTIFICATE

This is to certify that this Practical file is the bona fide work

of Master Ishant Sharma of Class XII, Roll No. ______

of New Era Public School, Dwarka, New Delhi, carried out

under my supervision.

Teacher’s Signature Principal’s Signature

2
INDEX
S. No. Practical Page Sign
Numbers

Based on DDL commands & DML command INSERT


1. 10
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”.
b) Create a table “TEAM” with following considerations:
a. It should have a column ‘TeamID’ for storing an integer value between 1 to 9,
which refers to
unique identification of a team.
b. Each ‘TeamID’ should have its associated name ‘TeamName’, which should be a
string of
length not less than 10 characters. Use the appropriate column-level constraint.
c. Using table level constraint, make ‘TeamID’ as the primary key.
c) Show the structure of the table TEAM using a SQL statement.
d) Add a new attribute ‘Team_Color’of size 10 characters to the table TEAM.
e) Insert these four rows in TEAM table:
a. Row 1: (1, Titan, Red)
b. Row 2: (2, Rockers, Blue)
c. Row 3: (3, Magnet, Yellow)
d. Row 3: (4, Hurricane, Green)
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.

g) Rename the attributes ‘FirstTeamScore’ and ‘SecondTeamScore’ to ‘FTscore’ and


‘STscore’
respectively.
h) Change the data type of ‘FTscore’ and ‘STscore’ to decimal..

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";

Queries Set 3 (Based on Aggregate Functions and GROUP BY clause)


3. Consider the following table ‘Gym’. Write SQL commands for (i)to(viii).
15

(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) Insert records as shown in the above table.


(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%.
(iii) Delete all the movies from the table with rating ‘C’.
(iv) Increase the price of all action movies by 5%. and thriller movies by 1%.
(v) Modify the price of the movie ‘Titanic’ to Rs 320.
(vi) Change the seats left for all action movies to 4.

Queries Set 5 (Based on Two Tables)


5. Write SQL queries for the two tables given below:
21

(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:

(i) To display CourseId, TeacherId, Name of Teacher, Phone Number of


Teachers living in Delhi.
(ii) To display the total fees charged by each teacher for the various courses.
(iii) To display the details of the teacher who charges the lowest fees.
(iv) To display TeacherID, Names of Teachers, Subjects of all teachers with
names starting with 'S'.
(v) To display SubjectCourseID, TeacherID, Teacher Name, and Phone
Number of teachers whose fees is more than 5000.

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.

(B) Write the output of the following SQL queries:


i. 6.57
ii. 4563.000
iii. 200.00
iv. 8.97
v. -1
vi. NES
vii. Wel
viii. PROGRAM
ix. 5
x. 15
xi. 166
xii. 15
xiii. June
xiv. Current date in YYYY-MM-DD format
xv. Current date and time

(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:

Roll No. Name Total Marks

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:

b) Create a table “TEAM” with following considerations:


a. It should have a column ‘TeamID’ for storing an integer value between 1 to 9, which
refers to unique identification of a team.
b. Each ‘TeamID’ should have its associated name ‘TeamName’, which should be a string of
length not less than 10 characters. Use the appropriate column-level constraint.
c. Using table level constraint, make ‘TeamID’ as the primary key.

Ans:

c) Show the structure of the table TEAM using a SQL statement.

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:

h) Change the data type of ‘FTscore’ and ‘STscore’ to decimal.

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:

(v) To display all different class sections.

Ans:

(vi) SELECT COUNT(*) FROM EXAM;

Ans:

(vii) SELECT Sname, Percentage FROM EXAM WHERE Name LIKE "N%";

Ans:

(viii) SELECT ROUND(Percentage, 0) FROM EXAM WHERE Adno = "R005";

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:

(v) To display the average age of each gender in the Gym.

Ans:

(vi) To display the sum of fees given in each membership type.

Ans:

16
(vii) To display the maximum fees given by monthly type members.

Ans:

(viii) To display the minimum fees given by each membership type.

Ans:

17
Practical 4:
Queries Set 4 ((Based on DML commands)
Write SQL commands for the following table MOVIE:

(i) Insert records as shown in the above table

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:

(v) Modify the price of the movie ‘Titanic’ to Rs 320.

Ans:

(vi) Change the seats left for all action movies to 4.

Ans:

20
Practical 5:
Queries Set 5 (Based on Two Tables)

Write SQL queries for the two tables given below.

(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:

(viii) Display total number of flights available for each Airlines

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)

Write SQL queries for the two tables given below.

(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

(A) Write SQL commands for the following operations:

a) To display the remainder of 175 and 5

Ans:

b) To display the cube of 24

Ans:

c) To display the number 563.854741 rounding off to the next hundred

Ans:

d) To find the square root of 625

Ans:

27
e) To convert 'welcome' into uppercase and 'FRIENDS' into lowercase

Ans:

f) To display 'DIA' from the word 'MEDIA'

Ans:

g) To find the number of characters in “InformationPractices”

Ans:

h) To display the current date and time

Ans:

i) To find the name of the weeday on 20th October 2016

Ans:

28
j) To display today’s date in DD/MM/YYYY format

(B) Write the output of the following SQL queries:

i. SELECT ROUND(6.5675, 2);

Ans:

ii. SELECT ROUND(4563.778, -3);

Ans:

iii. SELECT TRUNCATE(264.4367, -2);

Ans:

29
iv. SELECT TRUNCATE(8.975, 2);

Ans:

v. SELECT SIGN(-25);

Ans:

vi. SELECT MID('HONESTYWINS', 3, 4);

Ans:

vii. SELECT LEFT('WELCOME', 3);

Ans:

viii. SELECT RIGHT(CONCAT('PYTHON', 'PROGRAM'), 9);

Ans:

30
ix. SELECT INSTR('UNICODE', 'CO');

Ans:

x. SELECT DAYOFMONTH('2021-06-15');

Ans:

xi. SELECT DAYOFYEAR('2021-06-15');

Ans:

xii. SELECT DAY('2021-06-15');

Ans:

31
xiii. SELECT MONTHNAME('2021-06-15');

Ans:

xiv. SELECT CURDATE();

Ans:

xv. SELECT SYSDATE();

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")

choice = int(input("Enter your choice (1-7): "))

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

for char in str:


if char.isalpha()== True:
alphabets += 1
if char.isupper()== True:
upper += 1
else:
lower += 1
elif char.isdigit()== True:
digits += 1
elif char.isspace() == True:
spaces += 1
else:
special += 1

print("Number of alphabets:", alphabets)


print("Number of digits:", digits)
print("Number of uppercase letters:", upper)
print("Number of lowercase letters:", lower)
print("Number of whitespaces:", spaces)
print("Number of special characters:", special)

#MAIN PROGRAM

str = input("Enter a string: ")


count_char(str)

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)

y=(2*i)-1 #for getting alternate +ve, -ve sign


fact=math.factorial(y)
sum+=a*((x**y)/fact)

return(sum)

x=int(input("Enter the value of x: "))


n=int(input("Enter the number of terms: "))

ans=sin(x,n)

print(“The value of sin(",x,",",n,") is: ",ans))

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 binary_search(lst, n):


low = 0
high = len(lst) - 1
while low <= high:
mid = (low + high) // 2
if lst[mid] == n:
return mid
elif lst[mid] < n:
low = mid + 1
else:
high = mid - 1
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:

def series(first, last):


step = (last - first) // 3
lst = [ ]
for i in range(4):
value = first + (i * step)
lst.append(value)
return lst

# Main program
first_value = int(input("Enter the first value of the series: "))
last_value = int(input("Enter the last value of the series: "))

result = series(first_value, last_value)


print("Generated Series:", result)

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 = {}

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


words = file.read().split()

for word in words:


word = word.lower()
if word in word_frequency:
word_frequency[word] += 1
else:
word_frequency[word] = 1

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

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


lines = file.readlines()

for line in lines:


total_lines += 1
for char in line:
if char.isspace():
spaces += 1
elif char.isdigit():
digits += 1
elif char.isalpha():
alphabets += 1
else:
other += 1

print("Total spaces:", spaces)


print("Total lines:", total_lines)
print("Total digits:", digits)
print("Total alphabets:", alphabets)
print("Total other characters:", other)

# 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

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


text = file.read()
words = text.split()

for word in words:


total_words += 1
if len(word) > max_length:
max_length = len(word)
longest_word = word

print("Total words:", total_words)


print("Longest word:", longest_word)

# 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

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


for line in file:
total_lines += 1
if line.startswith('H'):
H_lines += 1
elif line.startswith('R'):
R_lines += 1
elif line.startswith('T'):
T_lines += 1
print("Total lines:", total_lines)
print("Lines starting with 'H':", H_lines)
print("Lines starting with 'R':", R_lines)
print("Lines starting with 'T':", T_lines)

# 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

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


text = file.read()

for char in text:


if char.isalpha():
if char.lower() in vowel:
vowels += 1
else:
consonants += 1

if char.isupper():
uppercase += 1
else:
lowercase += 1

print("Total vowels:", vowels)


print("Total consonants:", consonants)
print("Total uppercase characters:", uppercase)
print("Total lowercase characters:", lowercase)

# 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 write_records(filename, records):


with open(filename, 'wb') as file:
pickle.dump(records, file)

def read_records(filename):
try:
with open(filename, 'rb') as file:
records = pickle.load(file)
return records
except FileNotFoundError:
return []

def search_record(roll_number, records):


for record in records:
if record['roll_number'] == roll_number:
return record
return None

def update_marks(roll_number, new_marks, records):


for record in records:
if record['roll_number'] == roll_number:
record['marks'] = new_marks
return True
return False

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 add_record(filename, record):


try:
with open(filename, 'ab') as file:
pickle.dump(record, file)
except FileNotFoundError:
with open(filename, 'wb') as file:
pickle.dump(record, file)

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

print("Roll No.\tName\tTotal Marks")


for record in records:
total_marks = sum(record['marks_subjects'])
print(f"{record['rollno']}\t\t{record['name']}\t{total_marks}")

# 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(',')]

record = {'rollno': rollno, 'name': name, 'marks_subjects': marks}


add_record(filename, record)

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

# Function to add a new record to the file


def add_record():
emp_no = input("Enter Employee Number: ")
name = input("Enter Employee Name: ")
salary = float(input("Enter Salary: "))
bonus = salary * 0.1

record = {'empno': emp_no, 'name': name, 'salary': salary, 'bonus': bonus}

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.")

# Function to display all records in the file


def display_records():
try:
with open('emp', 'rb') as file:
while True:
try:
record = pickle.load(file)
print(record)
except EOFError:
break
except FileNotFoundError:
print("File 'emp' not found or empty.")

# Function to search for a record by employee number


def search_record():
emp_no = input("Enter Employee Number to search: ")
try:
with open('emp', 'rb') as file:
found = False
while True:
57
try:
record = pickle.load(file)
if record['empno'] == emp_no:
print("Record found:")
print(record)
found = True
break

except EOFError:
break
if not found:
print("Record not found.")
except FileNotFoundError:
print("File 'emp' not found or empty.")

# Function to delete a record by employee number


def delete_record():
emp_no = input("Enter Employee Number to delete: ")
try:
temp_file = 'temp_emp'
with open('emp', 'rb') as file, open(temp_file, 'wb') as temp:
while True:
try:
record = pickle.load(file)
if record['empno'] != emp_no:
pickle.dump(record, temp)
else:
print("Record deleted.")
except EOFError:
break

os.remove('emp')
os.rename(temp_file, 'emp')
except FileNotFoundError:
print("File 'emp' not found or empty.")

# Rest of the functions remain the same

# 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")

choice = input("Enter your choice (1-5): ")

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

# Function to write content to CSV file


def write_to_csv():
field_names = ['empno', 'empname', 'designation', 'salary']
employee_data = [
{'empno': '101', 'empname': 'Aniket', 'designation': 'Manager', 'salary': '60000'},
{'empno': '102', 'empname': 'Ishant', 'designation': 'Developer', 'salary': '50000'},
{'empno': '103', 'empname': 'Aryan', 'designation': 'Analyst', 'salary': '45000'}
]

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


writer = csv.DictWriter(file, fieldnames=field_names)
writer.writeheader()
writer.writerows(employee_data)
print("Data written to employee.csv successfully.")

# Function to read and display content from CSV file as a list


def read_from_csv():
try:
with open('employee.csv', newline='') as file:
reader = csv.DictReader(file)
data = list(reader)
print("Data read from employee.csv:")
for row in data:
print(row)
except FileNotFoundError:
print("File 'employee.csv' not found.")

# Writing data to CSV file


write_to_csv()

# Reading and displaying data from CSV file


read_from_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

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


reader = csv.reader(file)

print('Emp No', 'Emp Name', 'Designation', 'Salary')

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])

print(f"Total Records: {total_records}")


print(f"Total Salary: ${total_salary}")

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

def search_employee(file_name, emp_name):


with open(file_name, 'r') as file:
reader = csv.reader(file)

found_records = []

next(reader)

for row in reader:


if emp_name.lower() in row[1].lower():
found_records.append(row)

return found_records

file_name = 'employee.csv'
employee_name = input("Enter employee name to search: ")

records = search_employee(file_name, employee_name)

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 push(stack, item):


stack.append(item)
print("Pushed",item, " to the stack.")

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")

choice = input("Enter your choice (1-5): ")

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")

choice = input("Enter your choice (1-4): ")

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.execute("CREATE TABLE IF NOT EXISTS employee (id INT AUTO_INCREMENT


PRIMARY KEY, name VARCHAR(255), department VARCHAR(255))")

sql = "INSERT INTO employee (name, department) VALUES (%s, %s)"


val = [
("John Doe", "HR"),
("Jane Smith", "IT"),
("Alice Johnson", "Marketing")
]

mycursor.executemany(sql, val)

mydb.commit()

mycursor.execute("SELECT * FROM employee")


records = mycursor.fetchall()
print("Employee Records:")
for record in records:
print(record)

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

mydb = mysql.connector.connect(host="localhost", user="root", passwd='')


mycursor = mydb.cursor()

mycursor.execute("CREATE DATABASE IF NOT EXISTS Schooll")

import mysql.connector
conn = mysql.connector.connect(host="localhost", user="root", passwd='', database="Schooll")
mycur = conn.cursor()

ans = input('Do you want to add records? (yes/no): ')


if ans.lower() == 'yes':
while True:
mycur.execute("CREATE TABLE IF NOT EXISTS STUDENTS (ROLLNO INT, NAME
VARCHAR(20), GENDER CHAR(1), PERCENTAGE DECIMAL)")
sql = "INSERT INTO STUDENTS (ROLLNO, NAME, GENDER, PERCENTAGE) VALUES
(%s, %s, %s, %s)"
rn = input('Enter the ROLLNO of the student: ')
n = input('Enter the NAME of the student: ')
gender = input('Enter the GENDER of the student (f/m): ')
per = input('Enter the PERCENTAGE of the student: ')
value = (rn, n, gender, per)
try:
mycur.execute(sql, value)
print('Details of', n, 'added successfully')
conn.commit()
except mysql.connector.Error as err:
print('Please try again, unable to insert:', err)
ans = input('Do you want to add more records? (yes/no): ')
if ans.lower()=='no':
break

select_query = 'SELECT * FROM STUDENTS'


mycur.execute(select_query)

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()

def search_student_by_roll_and_delete(cursor, roll_no):


delete_query = 'DELETE FROM STUDENTS WHERE ROLLNO = %s'
cursor.execute(delete_query, (roll_no,))
return cursor.rowcount > 0

def update_student_name(cursor, roll_no, new_name):


update_query = 'UPDATE STUDENTS SET NAME = %s WHERE ROLLNO = %s'
cursor.execute(update_query, (new_name, roll_no))
return cursor.rowcount > 0

conn = mysql.connector.connect(host="localhost", user="root", passwd='ishu2006',


database="Schooll")
mycur = conn.cursor()
while True:
c=int(input("Main Menu\n1.Sort the records by names in ascending order\n2.Search a student
using roll number and delete\n3.Search a student using roll number and update\nPlease Enter your
choice(1/2/3) : "))
if c == 1:
sorted_records = sort_records_by_name(mycur)
print("Student Records (Sorted by Name in Ascending Order):")
if not sorted_records:
print("No records found.")
else:
for record in sorted_records:
# Convert Decimal to string
record_list = list(record)
record_list[3] = str(record_list[3])
print(tuple(record_list))

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: ")

if update_student_name(mycur, roll_to_update, new_name):


print(f"Record with ROLLNO {roll_to_update} updated successfully.")
conn.commit()
else:
print(f"No record found with ROLLNO {roll_to_update}. Update failed.")

else:
print("Invalid Choice")

mycur.close()
conn.close()

OUTPUT:

74

You might also like