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

shreyansh report file

The document is a report file for a Computer Science project submitted by Shreyansh Shrivas at The Aryans' School, Jhansi, for the academic year 2024-25. It includes a certificate of authenticity, an index of various programming tasks in Python, and detailed code examples for each task, covering topics such as functions, file handling, and data structures. The tasks involve practical applications of Python programming, including sorting algorithms, searching techniques, and data manipulation in CSV files.

Uploaded by

ayushshrivas110
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

shreyansh report file

The document is a report file for a Computer Science project submitted by Shreyansh Shrivas at The Aryans' School, Jhansi, for the academic year 2024-25. It includes a certificate of authenticity, an index of various programming tasks in Python, and detailed code examples for each task, covering topics such as functions, file handling, and data structures. The tasks involve practical applications of Python programming, including sorting algorithms, searching techniques, and data manipulation in CSV files.

Uploaded by

ayushshrivas110
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 64

THE ARYANS’ SCHOOL JHANSI

SESSION:2024-25
COMPUTER SCIENCE (083)
REPORT FILE

SUBMITTED TO: SUBMITTED BY:


MR.MANISH SHARMA SHREYANSH SHRIVAS
CLASS-12th D
CERTIFICATE

Name:- SHREYANSH SHRIVAS Class:-12-D


Institution:- The Aryans’ School, Jhansi
This is certified to be the bonafide work of the
student in the Computer Laboratory during the
academic year 2024-25.
Number of practicals certified 21 out of 21 in
the subject of Computer Science(083).

..………………………..
Teacher Incharge

……………………………… ………………………...
Examiner’s Signature Principal

Date:- …………………. Institution Rubber Stamp


INDEX
1. Write a function in Python to input a sentence and capitalize
each word.

2. Write a function that accepts a no. and check whether a no.


happy no. or not.

3. Write a function that takes 10 numbers in a List as argument


and sort them in ascending order using any sorting tehnique.
This function must return sorted list.
4. Write a function that takes a name as an argument and
search it in a List of names using Binary Search. If name
found, print “Search Successful” and also print its index
position.
5. Write a function which take two tuples seq_a and seq_b and
print True if every element in seq_a is also an element of
seq_b, else prints False.
6. Write a function that checks if two same values in a
dictionary have different keys. That is, for dictionary D1 =
{‘a’:10,’b’:20,’c’:10}, the function should print “2 keys have
same values” and for dictionary D2 = {‘a’:10,’b’:20,’c’:30}, the
function should print “No keys have same values”.
7. W. A. P. to input a Message (as Plain Text) and Convert it into
Cipher Text By embedding Encryption Key. Also, print the
Plain Text after Decryption. Use Library Function.
8. Write a function EUCount( ) in Python, which should reads
each character of a text file “IMP.txt”, should count and
display the occurrence of alphabets E and U (inclusing small
cases e and u too).
9. Write a function CountDig( ) in Python, which reads the
content of the text file “story.txt” and displays the no. of
digits in it.
10. Write a function displayRecord( ) in Python to display record
of employee ({name, age, salary}) which are stored in a csv
file EmpRecord.csv.
11. Write a Program in Python to write data of 5 students (which
should be input from user) into a CSV file “Record.csv”.

12. A csv file “Book.csv” has structure [BookNo, Book_Name,


Author, Price]. i. Write a user defined function CreateFile( )
to input data for a record and add to Book.csv. ii. Write a
function DisplayRec( ) in Python which display all the book
details which are stored in csv file “Book.csv”.
13. W. A. P. in Python to input data of 5 employee (name and
salary) using dictionary and store it in a binary file
EmpRecord.dat.
14. W. A. P. in Python to input a name from user and print the
record of that user from binary file MyRecord.dat. If file has
structure [name,age,per].
15. A binary file “MOBILE.DAT” has structure (Number, Calls).
Write a function display( ) in Python that would read
contents of the file “MOBILE.DAT” and display details of all
those mobile phones which have more than 1000 calls.
16. W. A. P. to implement STACK for book details [ISBN, name].

17. A. To display the names of all the items whose names starts
with “A”.
B. To display ICODEs and INAMEs of all items, whose Brand
name is Reliable or Coscore.
C. To change the Brand name to “Fit Trend India” of the item,
whose ICODE as”G101”.
D. Add a new row for new item in GYM with the details:
“G107”, “XYZ Exerciser”, 21000, “GTC Fitness”.
E. Delete items from table having price greater than 15000.
18. Write a Python code to create the table SALESPERSON with
given structure and constraint.

19. W. A. P. to input Details of Employee (EmpNo, Name, Age,


Salary) from user and store it in a Database Table Employee.
Also, display stored data on Monitor by extracting it from
Table.
20. W. A. P. to update price of product by 5% in Database Table
Product and print the details of Products with their updated
price.
21. W. A. P. to take Student Name from User who left the School
and delete the record from existing Database Table School
and print the detail of deleted record.
Q 1. WRITE A FUNCTION IN PYTHON TO INPUT A
SENTENCE AND CAPITALIZE EACH WORD ?
CODE:
#Program to capitalize each word
def capitalize(s):
words = s.split()
capitalized_words = []
for w in words:
capitalized_words.append(w.capitalize())
return ' '.join(capitalized_words)

#__main__
sentence = input("Enter a sentence: ")#function
invoking
print("Capitalised sentence is : ",capitalize(sentence))
OUTPUT:
Q 2. WRITE A FUNCTION THAT ACCEPTS A NO. &
CHECK WHETHER A NO. IS HAPPY NO. OR NOT?
CODE:
#program to check whether a no. is happy no. or not
def is_happy_number(n):
def sum_of_squares(num):
return sum(int(digit) ** 2 for digit in str(num))

visited = set()
while n != 1 and n not in visited:
visited.add(n)
n = sum_of_squares(n)

return n == 1

# Input and check


num = int(input("Enter a number: "))
print(f"{num} is a Happy Number!" if
is_happy_number(num) else f"{num} is not a Happy
Number!")
OUTPUT:
Q 3. WRITE A FUNCTION THAT TAKES 10 NO. IN A LIST AS
ARGUMENT & SORT THEM IN ASCENDING ORDER USING
MY SORTING TECHNIQUE ?
CODE:
#program that takes numbers and sorts them in
ascending order
def custom_sort():
# Take input from the user for 10 numbers
numbers = [int(input(f"Enter number {i+1}: ")) for i
in range(10)]

# Bubble Sort logic


for i in range(len(numbers) - 1):
for j in range(len(numbers) - 1 - i):
if numbers[j] > numbers[j + 1]:
numbers[j], numbers[j + 1] = numbers[j + 1],
numbers[j]

print("Sorted numbers:", numbers)

custom_sort() #function invoking


OUTPUT:
Q 4. WRITE A FUNCTION THAT TAKES A NAME AS AN
ARGUMENT & SEARCH IT IN A LIST OF NAMES USING
BINARY SEARCH.IF NAME FOUND ,PRINT “SEARCH
SUCCESSFUL” & PRINT ITS INDEX POSITION ?
CODE:
#program that take names and searches it by binary search
def binary_search(names, target):
names.sort()
for low, high in [(0, len(names) - 1)]:
while low <= high:
mid = (low + high) // 2
if names[mid] == target:
print(f"Search successful! Name '{target}' found at index
{mid}.")
return
elif names[mid] < target:
low = mid + 1
else:
high = mid - 1
print("Search unsuccessful. Name not found.")

# Get input using a for loop for names


names_list = [name.strip() for name in input("Enter names (comma-
separated): ").split(',')]
target_name = input("Enter name to search: ")
binary_search(names_list, target_name)
OUTPUT:
Q 5. WRITE A FUNC. WHICH TAKE 2 TUPLES SEQ-a
&SEQ-b & PRINT TRUE IF EVERY ELEMENT IN SEQ-a IS
ALSO AN ELEMENT OF SEQ-b , ELSE PRINT FALSE ?
CODE:
#program that takes 2 tuples and checks if allelements in
seq_a also in seq_b
def check_elements_in_b(seq_a, seq_b):
if all(element in seq_b for element in seq_a):
print(True)
else:
print(False)
SEQ_a = (1, 2, 3)
SEQ_b = (3, 2, 1, 4, 5)
check_elements_in_b(SEQ_a, SEQ_b)
SEQ_a = (1, 5, 7)
SEQ_b = (3, 2, 1, 4, 5)
check_elements_in_b(SEQ_a, SEQ_b)
OUTPUT:
Q 6. WRITE A FUNCTION THAT CHEKS IF 2 SAME VALUES IN A
DICTIONARY HAVE DIFFERENT KEYS ,I.E FOR DICTIONARY
D1={‘A’:10,’B’:20,’C’:10} THE FUNC. PRINT 2 KEYS HAVE SAME
VALUES FOR DICTIONARY D2={‘A’:10,’B’:20,’C’:30},THE FUNC.
SHOULD PRINT “NO KEYS HAVE SAME VALUES” ?
CODE: #program that checks if a dictionary key have same values or
not
def check_duplicate_values(d):
value_to_keys = {}
for key, value in d.items():
value_to_keys.setdefault(value, []).append(key)
for keys in value_to_keys.values():
if len(keys) > 1:
print(f"Keys {keys} have the same value {keys[0]}")
return
print("NO KEYS HAVE SAME VALUES")
# Get user input and process it
def get_user_input():
d = {}
while True:
key = input("Enter key (or 'done' to finish): ")
if key.lower() == 'done':
break
value = int(input(f"Enter value for key '{key}': "))
d[key] = value
check_duplicate_values(d)
get_user_input()
OUTPUT:
Q 7. W.A.P TO INPUT A MSG.(AS PLAIN TEXT) &
CONVERT IT INTO CIPHER TEXT BY EMBEDDING
ENCRYPTION KEY. ALSO PRINT THE PLAIN TEXT
AFTER DECRYPTION USING FUNC.?
CODE:
#progarm to input a string and convert it into
encrypted string
def encrypt(text, special_char):
return "".join(c + special_char for c in text)

def decrypt(text, special_char):


return text.replace(special_char, "")

# Input text and special character


plain_text = input("Enter plain text: ")
special_char = input("Enter special character to insert:
")

# Encrypt and decrypt


cipher_text = encrypt(plain_text, special_char)
print("Cipher Text:", cipher_text)
print("Decrypted Text:", decrypt(cipher_text,
special_char))
OUTPUT:
Q 8. WRITE A FUNCTION eucount() IN PYTHON,
WHICH SHOULD READ EACH CHARACTER OF A TXT.
FILE “IMP.TXT”,SHOULD COUNT & DISPLAY THE
OCCURANCE OF ALPHABETS E & U ?
CODE:
def euCount():
# Ask user for input text
user_input = input("Enter the text to be written to the file:
")

# Open the file in write mode to create or overwrite it


with user input
with open("IMP.TXT", "w") as file:
file.write(user_input + "\n") # Write user input to the
file

# Initialize counters for 'e' and 'u'


count_e = 0
count_u = 0

# Open the file in read mode to read each character


with open("IMP.TXT", "r") as file:
text = file.read() # Read the entire content of the file

# Loop through each character in the file content


for char in text:
if char.lower() == 'e': # Check if the character is 'e' or
'E'
count_e += 1
elif char.lower() == 'u': # Check if the character is 'u'
or 'U'
count_u += 1

# Display the counts of 'e' and 'u'


print(f"Occurrences of 'E' or 'e': {count_e}")
print(f"Occurrences of 'U' or 'u': {count_u}")

euCount() # function invoking


OUTPUT:

FROM TEXT FILE:-


Q 9. WRITE A FUNCTION CountDig() IN PYTHON,WHICH RESULTS
THE CONTENT OF THE TEXT FILE “STORY.TXT” &DISPLAY THE NO.
OF DIGITS IN IT ?
CODE: #function to count the no of digits in a text file
def CountDig():
# Ask the user to input text
user_input = input("Enter the text to be written to the file: ")

file = open("STORY.TXT", "w")


file.write(user_input)
file.close()

count_digits = 0

# Open the file in read mode to count digits


file = open("STORY.TXT", "r")
text = file.read() # Read the entire content of the file

for char in text:


if char.isdigit(): # Check if the character is a digit
count_digits += 1

file.close()
# Display the count of digits
print(f"Number of digits in the file: {count_digits}")

CountDig() #function invoking


OUTPUT:

FROM TEXT FILE:-


Q 10. Write a function displayRecord( ) in Python to
display record of employee ({name, age, salary})
which are stored in a csv file EmpRecord.csv.
CODE:
import csv

def writeRecord():
# Open the file in append mode to add new records
file = open('EmpRecord.csv', mode='a', newline='')
writer = csv.DictWriter(file, fieldnames=['name', 'age', 'salary'])

# Write the header only if the file is empty


if file.tell() == 0:
writer.writeheader()

# Get user input for new records


while True:
name = input("Enter employee name: ")
age = input("Enter employee age: ")
salary = input("Enter employee salary: ")

writer.writerow({'name': name, 'age': age, 'salary': salary})

# Asking if the user wants to add more records


more = input("Do you want to add another record? (yes/no):
").strip().lower()
if more != 'yes':
break

file.close()
def displayRecord():
# Open the file
file = open('EmpRecord.csv', mode='r')
reader = csv.DictReader(file)

# Print the header


print(f"{'Name':<20}{'Age':<10}{'Salary':<10}")
print("-" * 40)

# Loop through each record and print the details


for row in reader:
print(f"{row['name']:<20}{row['age']:<10}{row['salary']:<10}")
file.close()
# Write records and then display them
writeRecord()
displayRecord()
OUTPUT:

FROM CSV FILE:


Q 11. Write a Program in Python to write data of 5
students (which should be input from user) into a
CSV file “Record.csv”.
CODE:
import csv
def writeStudentRecords():
file = open('Record.csv', mode='w', newline='')
writer = csv.DictWriter(file, fieldnames=['Name', 'Age', 'Grade'])
writer.writeheader()

for i in range(1, 6):


print(f"Enter details for Student {i}:")
name = input("Name: ")
age = input("Age: ")
grade = input("Grade: ")

writer.writerow({'Name': name, 'Age': age, 'Grade': grade})


print()

file.close()
print("Data for 5 students has been written to 'Record.csv'.")

writeStudentRecords() #function invoking


OUTPUT:

FROM CSV FILE:


Q 12. A csv file “Book.csv” has structure [BookNo,
Book_Name, Author, Price]. i. Write a user defined
function CreateFile( ) to input data for a record and
add to Book.csv. ii. Write a function DisplayRec( ) in
Python which display all the book details which are
stored in csv file “Book.csv”.
CODE:
import csv

def CreateFile():

file = open('Book.csv', mode='a', newline='')


writer = csv.DictWriter(file, fieldnames=['BookNo',
'Book_Name', 'Author', 'Price'])

if file.tell() == 0:
writer.writeheader()

book_no = input("Enter Book Number: ")


book_name = input("Enter Book Name: ")
author = input("Enter Author Name: ")
price = input("Enter Price: ")

writer.writerow({'BookNo': book_no, 'Book_Name':


book_name, 'Author': author, 'Price': price})
file.close()
print("Record added to 'Book.csv'.")

def DisplayRec():

file = open('Book.csv', mode='r')


reader = csv.DictReader(file)

# Print the header


print(f"{'BookNo':<10}{'Book_Name':<20}{'Author':<20}
{'Price':<10}")
print("-" * 60)

# Loop through each record and print the details


for row in reader:
print(f"{row['BookNo']:<10}{row['Book_Name']:<20}
{row['Author']:<20}{row['Price']:<10}")

file.close()

print("Choose an option:")
print("1. Add a new book record")
print("2. Display all book records")

choice = input("Enter your choice (1/2): ").strip()


if choice == '1':
CreateFile()
elif choice == '2':
DisplayRec()
else:
print("Invalid choice.")
OUTPUT:

FROM CSV FILE


Q 13. W. A. P. in Python to input data of 5
employee (name and salary) using dictionary
and store it in a binary file EmpRecord.dat.
CODE:
#program to input data of 5 emplyees and store it in a binary file

import pickle

def get_data():
data = {}
for i in range(5):
name = input(f"Enter name of employee {i + 1}: ")
salary = float(input(f"Enter salary of {name}: "))
data[name] = salary
return data

def save_file(file, data):


with open(file, 'wb') as f:
pickle.dump(data, f)
print(f"Data saved to {file}.")

data = get_data() #function invoking


save_file("EmpRecord.dat", data)
OUTPUT:

FROM BINARY FILE:


Q 14. W. A. P. in Python to input a name from
user and print the record of that user from
binary file MyRecord.dat. If file has structure
[name,age,per].
CODE:
import pickle
def write_data(filename):
data = []
for i in range(3):
name = input(f"Enter name of employee {i + 1}: ")
age = int(input(f"Enter age of {name}: "))
percentage = float(input(f"Enter percentage of {name}: "))
data.append([name, age, percentage])

with open(filename, 'wb') as file:


pickle.dump(data, file)
print(f"Data has been written to {filename}.")

def search_record(filename, name):


with open(filename, 'rb') as file:
records = pickle.load(file)
for record in records:
if record[0].lower() == name.lower():
return record
return None
filename = "MyRecord.dat"
write_data(filename)
name = input("Enter the name to search: ")
result = search_record(filename, name)
if result:
print(f"Record Found: Name: {result[0]}, Age: {result[1]},
Percentage: {result[2]}%")
else:
print("Record not found.")
OUTPUT:

FROM BINARY FILE:


Q 15. A binary file “MOBILE.DAT” has structure (Number,
Calls). Write a function display( ) in Python that would
read contents of the file “MOBILE.DAT” and display
details of all those mobile phones which have more than
1000 calls.
CODE:
import pickle
def write_data():
n = int(input("How many records? "))
data = []
for _ in range(n):
number = input("Enter mobile number: ")
calls = int(input("Enter number of calls: "))
data.append((number, calls))

with open("MOBILE.DAT", 'wb') as file:


pickle.dump(data, file)
def display():
with open("MOBILE.DAT", 'rb') as file:
records = pickle.load(file)

print("\nNumbers with more than 1000 calls:")


for number, calls in records:
if calls > 1000:
print(f"Number: {number}, Calls: {calls}")

write_data() #function invoking


display() #function invoking
OUTPUT:

FROM BINARY FILE:


Q 16. W. A. P. to implement STACK for book details
[ISBN, name].
CODE:
book_stack = []

# Function to push a book onto the stack


def push(stack, isbn, name):
stack.append({'ISBN': isbn, 'name': name})

# Function to pop a book


def pop(stack):
return stack.pop() if stack else "Stack is empty."

# Function to peek at the top book


def peek(stack):
return stack[-1] if stack else "Stack is empty."

# Function to display all books


def display(stack):
if not stack:
print("Stack is empty.")
else:
for book in stack:
print(f"ISBN: {book['ISBN']}, Name: {book['name']}")
# Push some books onto the stack
push(book_stack, '978-3-16-148410-0', 'The Great Gatsby')
push(book_stack, '978-1-4028-9467-7', '1984')
push(book_stack, '978-0-7432-7356-5', 'The Catcher in the Rye')

# Display all books in the stack


print("Books in stack:")
display(book_stack)

# Pop a book
print("\nPopped book:", pop(book_stack))

# To Display remaining books


print("\nBooks in stack after pop:")
display(book_stack)

# Peek at the top book


print("\nPeeked book:", peek(book_stack))
OUTPUT:
Q 17. A. To display the names of all the items whose
names starts with “A”.
B. To display ICODEs and INAMEs of all items, whose
Brand name is Reliable or Coscore.
C. To change the Brand name to “Fit Trend India” of the
item, whose ICODE as”G101”.
D. Add a new row for new item in GYM with the details:
“G107”, “XYZ Exerciser”, 21000, “GTC Fitness”
E. Delete items from table having price greater than
15000.
CREATING DATABASE AND TABLE:
CODES AND THEIR OUTPUTS:
A.

B.

C.

D.
E.
Q 18. Write a Python code to create the table
SALESPERSON with given structure and constraint.
CODE:
import mysql.connector

conn=mysql.connector.connect(host="localhost",user="root",password=
"root ",database="computer")

# Create a cursor object to interact with the database


cursor = conn.cursor()

# Create the SALESPERSON table


cursor.execute('''
CREATE TABLE IF NOT EXISTS SALESPERSON (
SCODE DECIMAL(6) PRIMARY KEY,
FIRSTNAME VARCHAR(30),
LASTNAME VARCHAR(30) NOT NULL,
CITY VARCHAR(30) NOT NULL,
SALES DECIMAL(8)
);
''')
# Commit the transaction and close the connection
conn.commit()
conn.close()
print("Database 'computer' and table 'SALESPERSON' created
successfully!")
OUTPUTS:
Q 19. W. A. P. to input Details of Employee (EmpNo,
Name, Age, Salary) from user and store it in a
Database Table Employee. Also, display stored data
on Monitor by extracting it from Table.
CODE:
import mysql.connector

conn = mysql.connector.connect(
host="localhost",
user="root",
password="root ",
database="employee"
)
cursor = conn.cursor()

cursor.execute('''
CREATE TABLE IF NOT EXISTS Employee (
EmpNo INT PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
Age INT NOT NULL,
Salary DECIMAL(10, 2) NOT NULL
)
''')
emp_no = int(input("Enter Employee Number (EmpNo): "))
name = input("Enter Employee Name: ")
age = int(input("Enter Employee Age: "))
salary = float(input("Enter Employee Salary: "))

cursor.execute('''
INSERT INTO Employee (EmpNo, Name, Age, Salary)
VALUES (%s, %s, %s, %s)
''', (emp_no, name, age, salary))

# Commit the transaction to the database


conn.commit()

print(f"Employee data for {name} has been added successfully.")

# Close the connection to the database


cursor.close()
conn.close()
OUTPUTS:
FROM SQL:
Q 20. W. A. P. to update price of product by 5%
in Database Table Product and print the details
of Products with their updated price.
CODE:
import mysql.connector

def create_table():
# Connect to the database
conn = mysql.connector.connect(
host="localhost",
user="root",
password="root ",
database="product"
)
cursor = conn.cursor()

# Create table if it does not exist


cursor.execute('''
CREATE TABLE IF NOT EXISTS Product (
ProductID INT PRIMARY KEY,
ProductName VARCHAR(100),
Price FLOAT
)
''')
conn.commit() # Commit the changes
conn.close()

def insert_sample_data():
# Connecting to the database
conn = mysql.connector.connect(
host="localhost",
user="root",
password="Tiger@1234",
database="product"
)
cursor = conn.cursor()

# Sample product data


products = [
(101, 'Laptop', 1000),
(102, 'Smartphone', 500),
(103, 'Tablet', 300),
(104, 'Headphones', 150),
(105, 'Smartwatch', 200)
]

# Inserting sample data


cursor.executemany('''
INSERT IGNORE INTO Product (ProductID, ProductName,
Price)
VALUES (%s, %s, %s)
''', products)
conn.commit() # Commit the changes
conn.close()
print("Sample product data has been added.")

def update_price():
# Connect to the database
conn = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="product"
)
cursor = conn.cursor()

# Update prices by 5%
cursor.execute('''
UPDATE Product
SET Price = Price * 1.05
''')
conn.commit() # Commit the changes
print("Prices updated by 5%.")
conn.close() # Close the connection

def display_products():
# Connect to the database
conn = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="product"
)
cursor = conn.cursor()

# Fetch all products


cursor.execute('SELECT * FROM Product')
rows = cursor.fetchall()

# Display product details


if rows:
print("Product Details (with updated prices):")
for row in rows:
print(f"ProductID: {row[0]}, ProductName: {row[1]}, Price:
{row[2]:.2f}")
else:
print("No products found.")
conn.close() # Close the connection
# Main function to run the program
def main():
create_table() # Create table if not already created
insert_sample_data() # Add sample products to the table
update_price() # Update prices by 5%
display_products() # Display the updated products

# Run the main function


if __name__ == "__main__":
main()
OUTPUTS:
Q 21. W. A. P. to take Student Name from User
who left the School and delete the record from
existing Database Table School and print the
detail of deleted record.
CODE:
import mysql.connector

def del_record(name):
db = mysql.connector.connect(
host="localhost",
user="root",
password="root",
database="school"
)
cur = db.cursor()

# Fetch the record before deleting


query = "SELECT * FROM School WHERE name = %s"
cur.execute(query, (name,))
rec = cur.fetchone()

if rec:
# Print details of the record to be deleted
print("Deleting the following record:")
print(f"ID: {rec[0]}, Name: {rec[1]}, Details: {rec[2:]}")

# Delete the record


del_query = "DELETE FROM School WHERE name = %s"
cur.execute(del_query, (name,))
db.commit()

print("Record deleted successfully.")


else:
print("No record found for:", name)

# Close the database connection


cur.close()
db.close()

# Get student name from the user


name = input("Enter the name of the student to delete: ")
del_record(name)
OUTPUTS:

You might also like