0% found this document useful (0 votes)
49 views58 pages

Document 1

The document outlines a series of Python programming exercises focusing on file handling, including functions for counting words, searching names, copying text, and manipulating CSV files. Each task includes a function definition, example code, and expected outputs. The exercises cover various file operations such as reading, writing, and updating data in text and binary formats.

Uploaded by

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

Document 1

The document outlines a series of Python programming exercises focusing on file handling, including functions for counting words, searching names, copying text, and manipulating CSV files. Each task includes a function definition, example code, and expected outputs. The exercises cover various file operations such as reading, writing, and updating data in text and binary formats.

Uploaded by

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

PRACTICAL JOURNAL –GOKUL GIRISH

1. Write a function COUNTWORDS (), to count the number of words in each line of a text file
“POEM.TXT”

Answer:

def COUNTWORDS(file):

string = file.read()

w=string.split()

print("number of words:",len(w))

file = open("Q1\POEM.txt","r")

COUNTWORDS(file)

Content: oh my god is that a big cute turtle

Output:

2. Write a function SNAME (), to create a text file “names.txt” and search for a name.

Answer:

def SNAME(file):

num = int(input("enter how many times to write:"))

for i in range(num):

nam = input("enter name:")

file.write(nam+" ")

file.close()

file = open('Q2/names.txt',"r")

s=input("enter the name to search :")

st=file.read()
w-string.split()

Found = False

for i in w:

if i == s:

Found = False

break

if Found == True:

print("name is found")

else:

print("name is not found")

file.close()

file = open('Q2/names.txt',"w")

SNAME(file)

Output:

3. Write a function COPYTEXT () to create a text file “story.txt” copy all sentences starting with
‘t‘into a new file “temp.txt” and print it.

Answer:

def COPYTEXT():

with open("story.txt", "w") as file:


file.write("This is a simple story.\n")

file.write("The sun is shining.\n")

file.write("Once upon a time, there was a brave knight.\n")

file.write("The knight fought against dragons.\n")

file.write("He traveled far and wide.\n")

file.write("Every adventure taught him valuable lessons.\n")

print("A story has been written to 'story.txt'.")

sentences_with_t = []

with open("story.txt", "r") as file:

sentences = file.readlines()

for sentence in sentences:

if sentence.strip().lower().startswith('t'):

sentences_with_t.append(sentence.strip())

with open("temp.txt", "w") as temp_file:

for sentence in sentences_with_t:

temp_file.write(sentence + "\n")

print("Sentences starting with 't' have been copied to 'temp.txt':")

for sentence in sentences_with_t:

print(sentence)

COPYTEXT()
OUTPUT:

4. Write a function COPYB (), to copy all word starting with ‘b’ into a new file.

ANSWER:

def COPYB():

with open("story.txt", "w") as file:

file.write("This is a simple story about brave knights.\n")

file.write("The sun is shining brightly.\n")

file.write("Once upon a time, there was a big battle.\n")

file.write("The knights fought bravely for their kingdom.\n")

file.write("Every adventure brought new challenges.\n")

print("A story has been written to 'story.txt'.")

b_words = []

with open("story.txt", "r") as file:


for line in file:

words = line.split()

for word in words:

if word.lower().startswith('b'):

b_words.append(word.strip('.,!?"\''))

with open("b_words.txt", "w") as b_file:


for word in b_words:

b_file.write(word + "\n")

print("Words starting with 'b' have been copied to 'b_words.txt':")

for word in b_words:

print(word)

COPYB()

OUTPUT:

5. Write a function HESHE (), to count the number of times the word ‘he’ or ‘she’ appears in
story.txt

Answer:
def HESHE():

with open("story.txt", "r") as file:

content = file.read()

he_count = content.lower().count("he")

she_count = content.lower().count("she")
total_count = he_count + she_count

print(f"The word 'he' appears {he_count} times.")

print(f"The word 'she' appears {she_count} times.")

print(f"Total occurrences of 'he' and 'she': {total_count}")

HESHE()

Output:

6. Write a function PALIN (),to search and print all palindrome words from story.txt.

Answer:

def PALIN():

with open("story.txt", "r") as file:

content = file.read()

words = content.split()

palindromes = []

for word in words:

cleaned_word = word.strip('.,!?"\'').lower()

if cleaned_word == cleaned_word[::-1] and len(cleaned_word) > 1:

palindromes.append(cleaned_word)

print("Palindrome words found in 'story.txt':")


for palindrome in palindromes:

print(palindrome)

PALIN()

Content:

Output:

7. Write a function LINE ()to read a text file line by line and display each word separated by
a#

Answer:

def LINE():

with open("story.txt", "r") as file:

for line in file:

words = line.split()

formatted_line = "#".join(words)

print(formatted_line)

LINE()

Content:
Output:

8. Write a function CHARACTER (), to read a text file and display the number of
vowels/consonants/uppercase/lowercase characters in the file.

Answer:

def CHARACTER():

vowels = "aeiouAEIOU"

consonants = "bcdfghjklmnpqrstvwxyzBCDFGHJKLMNPQRSTVWXYZ"

vowel_count = 0

consonant_count = 0

uppercase_count = 0

lowercase_count = 0

with open("story.txt", "r") as file:

content = file.read()
for char in content:

if char.isalpha():

if char in vowels:

vowel_count += 1

elif char in consonants:

consonant_count += 1

if char.isupper():

uppercase_count += 1

elif char.islower():

lowercase_count += 1

print(f"Number of vowels: {vowel_count}")

print(f"Number of consonants: {consonant_count}")

print(f"Number of uppercase characters: {uppercase_count}")

print(f"Number of lowercase characters: {lowercase_count}")

CHARACTER()

Content:

Output:
9. Write a function REMOVEA (),to remove all the lines that starts with the character 'a' in a file
and write it to another file.

Answer:

def REMOVEA():

with open("story.txt", "r") as file:

lines = file.readlines()

with open("filtered_story.txt", "w") as new_file:

for line in lines:

if not line.startswith('a') and not line.startswith('A'):

new_file.write(line)

print("Lines starting with 'a' have been removed and saved to 'filtered_story.txt'.")

REMOVEA()

Content(after execution)

Output:
10. Write a function DISPLAYWORDS() in Python to read lines from a text file “POEM.TXT”
and display those words which are less than 4 characters.

Answer:

def DISPLAYWORDS():

with open("POEM.TXT", "r") as file:

content = file.readlines()

short_words = []

for line in content:

words = line.split()

for word in words:

if len(word) < 4:

short_words.append(word)

print("Words with less than 4 characters:")

for word in short_words:

print(word)

DISPLAYWORDS()

Content:
Output:

11. Write a function to create a CSV file by entering user-id and password, read and search the
password for given user id.

Answer:

import csv

def create_user_csv():

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

writer = csv.writer(file)

writer.writerow(["User ID", "Password"])

while True:

user_id = input("Enter User ID (or type 'exit' to finish): ")

if user_id.lower() == 'exit':

break

password = input("Enter Password: ")

writer.writerow([user_id, password])

def search_password():

user_id_to_search = input("Enter User ID to search for the password: ")

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


reader = csv.reader(file)

next(reader) # Skip the header row

found = False

for row in reader:

if row[0] == user_id_to_search:

print(f"Password for User ID '{user_id_to_search}': {row[1]}")

found = True

break

if not found:

print(f"No password found for User ID '{user_id_to_search}'.")

def main():

create_user_csv()

search_password()

main()

Content:

Output:
Searching for network.

If the user id is not found

12.. Create a csv file with fields bno, name, type, and price. Write a menu driven program using
functions:

1. To already existing book.csv add more data

2. To existing book.csv if type is fiction increase price by 20, update the file

3. Display the file

4. Counting the number of book belonging to type “Comedy”

5. Delete a particular record from the file book.csv.

Answer:

import csv

import os

def create_csv():

if not os.path.exists("book.csv"):

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

writer = csv.writer(file)

writer.writerow(["bno", "name", "type", "price"])

print("CSV file 'book.csv' created.")

else:

print("CSV file 'book.csv' already exists.")


def add_data():

with open("book.csv", "a", newline='') as file:

writer = csv.writer(file)

bno = input("Enter Book Number (bno): ")

name = input("Enter Book Name: ")

book_type = input("Enter Book Type: ")

price = input("Enter Book Price: ")

writer.writerow([bno, name, book_type, price])

print("Record added successfully.")

def increase_price_fiction():

updated_rows = []

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

reader = csv.reader(file)

header = next(reader)

updated_rows.append(header)

for row in reader:

if row[2].lower() == "fiction":

row[3] = str(float(row[3]) + 20) # Increase price by 20

updated_rows.append(row)

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

writer = csv.writer(file)

writer.writerows(updated_rows)
print("Prices updated for fiction books.")

def display_file():

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

reader = csv.reader(file)

print("Records in 'book.csv':")

for row in reader:

print(row)

def count_comedy_books():

comedy_count = 0

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

reader = csv.reader(file)

next(reader) # Skip header

for row in reader:

if row[2].lower() == "comedy":

comedy_count += 1

print(f"Number of books belonging to type 'Comedy': {comedy_count}")

def delete_record():

bno_to_delete = input("Enter the Book Number (bno) to delete: ")

updated_rows = []

found = False

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

reader = csv.reader(file)
header = next(reader)

updated_rows.append(header)

for row in reader:

if row[0] != bno_to_delete:

updated_rows.append(row)

else:

found = True

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

writer = csv.writer(file)

writer.writerows(updated_rows)

if found:

print(f"Record with bno '{bno_to_delete}' has been deleted.")

else:

print(f"No record found with bno '{bno_to_delete}'.")

def main_menu():

create_csv() # Create the CSV file initially

while True:

print("\nMenu:")

print("1. Add more data to existing book.csv")

print("2. Increase price by 20 for fiction books")

print("3. Display the file")

print("4. Count the number of books belonging to type 'Comedy'")


print("5. Delete a particular record from book.csv")

print("6. Exit")

choice = input("Enter your choice: ")

if choice == '1':

add_data()

elif choice == '2':

increase_price_fiction()

elif choice == '3':

display_file()

elif choice == '4':

count_comedy_books()

elif choice == '5':

delete_record()

elif choice == '6':

print("Exiting the program.")

break

else:

print("Invalid choice! Please choose again.")

main_menu()

Output:
If i chose:

1.

2.

3.

4.
5.

6.

13. Create a CSV file called stud.csv with fields sno,sname,stream and marks.Write a function
csvcopy(), to copy the contents of stud.csv to class.csv.

Answer:

import csv

import os

def create_stud_csv():

# Create 'stud.csv' and write some sample data if it doesn't exist

if not os.path.exists("stud.csv"):

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

writer = csv.writer(file)

writer.writerow(["sno", "sname", "stream", "marks"])

# Sample data

writer.writerow([1, "Alice", "Science", 85])

writer.writerow([2, "Bob", "Arts", 90])

writer.writerow([3, "Charlie", "Commerce", 78])

print("CSV file 'stud.csv' created with sample data.")

def csvcopy():

# Copy contents from 'stud.csv' to 'class.csv'

with open("stud.csv", "r") as source_file:

reader = csv.reader(source_file)
with open("class.csv", "w", newline='') as dest_file:

writer = csv.writer(dest_file)

for row in reader:

writer.writerow(row)

print("Contents copied from 'stud.csv' to 'class.csv'.")

def main():

create_stud_csv() # Create stud.csv with sample data

csvcopy() # Copy contents to class.csv

if __name__ == "__main__":

main()

Content:

Stud.csv and class.csv

Output;

14. Create a binary file emp.dat which have n dictionaries with fields ecode, ename, designation
and salary. Write a menu driven program using functions for:

1. appending

2. displaying

3. searching (for a particular employee based on ecode)


4. Updating salary by 500 if designation is manager, 200 if operator

Answer:

import pickle

import os

def create_emp_file():

if not os.path.exists("emp.dat"):

with open("emp.dat", "wb") as file:

pass # Just create the file if it doesn't exist

def append_employee():

employee = {}

employee['ecode'] = input("Enter Employee Code: ")

employee['ename'] = input("Enter Employee Name: ")

employee['designation'] = input("Enter Designation: ")

employee['salary'] = float(input("Enter Salary: "))

with open("emp.dat", "ab") as file:

pickle.dump(employee, file)

print("Employee record added successfully.")

def display_employees():

print("Employee Records:")

with open("emp.dat", "rb") as file:

try:

while True:
employee = pickle.load(file)

print(employee)

except EOFError:

pass

def search_employee():

ecode_to_search = input("Enter Employee Code to search: ")

found = False

with open("emp.dat", "rb") as file:

try:

while True:

employee = pickle.load(file)

if employee['ecode'] == ecode_to_search:

print("Employee found:", employee)

found = True

break

except EOFError:

if not found:

print("Employee with code", ecode_to_search, "not found.")

def update_salary():

with open("emp.dat", "rb+") as file:

try:

while True:

pos = file.tell()

employee = pickle.load(file)
if employee['designation'].lower() == 'manager':

employee['salary'] += 500

elif employee['designation'].lower() == 'operator':

employee['salary'] += 200

file.seek(pos) # Go back to the position to update the record

pickle.dump(employee, file)

file.flush() # Ensure the data is written to the file

except EOFError:

print("Salaries updated successfully.")

def main_menu():

create_emp_file()

while True:

print("\nMenu:")

print("1. Append Employee Record")

print("2. Display All Employee Records")

print("3. Search Employee by Ecode")

print("4. Update Salaries")

print("5. Exit")

choice = input("Enter your choice: ")

if choice == '1':

append_employee()

elif choice == '2':


display_employees()

elif choice == '3':

search_employee()

elif choice == '4':

update_salary()

elif choice == '5':

print("Exiting the program.")

break

else:

print("Invalid choice! Please choose again.")

if __name__ == "__main__":

main_menu()

OUTPUT:

If i chose:

1.
2.

3.

4.

5.

15. Write a function to make a new file with only managers and print name of manager with
highest salary.

Answer;
import pickle

import os

def create_manager_file():

managers = []

with open("emp.dat", "rb") as file:

try:

while True:

employee = pickle.load(file)
if employee['designation'].lower() == 'manager':

managers.append(employee)

except EOFError:

pass

with open("managers.dat", "wb") as file:

for manager in managers:

pickle.dump(manager, file)

if managers:

highest_salary_manager = max(managers, key=lambda x: x['salary'])

print(f"Manager with the highest salary: {highest_salary_manager['ename']} with salary


{highest_salary_manager['salary']}")

else:

print("No managers found.")

def main():

create_manager_file()

if __name__ == "__main__":

main()

Emp.dat contains:
Output becomes to be;

16. Write a function to insert a new record assuming details are in ascending order of ecode:

1. Create a binary file of list

2. Display it

3. Sort it

Answer;
import pickle

import os

def create_employee_file():

employees = [

{'ecode': 'E001', 'ename': 'Alice', 'designation': 'Manager', 'salary': 5000},

{'ecode': 'E002', 'ename': 'Bob', 'designation': 'Operator', 'salary': 3000},

{'ecode': 'E003', 'ename': 'Charlie', 'designation': 'Manager', 'salary': 6000}

with open("employees.dat", "wb") as file:

for employee in employees:

pickle.dump(employee, file)

def display_employees():

print("Employee Records:")

with open("employees.dat", "rb") as file:

try:
while True:

employee = pickle.load(file)

print(employee)

except EOFError:

pass

def insert_employee(new_employee):

employees = []

with open("employees.dat", "rb") as file:

try:

while True:

employee = pickle.load(file)

employees.append(employee)

except EOFError:

pass

employees.append(new_employee)

employees.sort(key=lambda x: x['ecode'])

with open("employees.dat", "wb") as file:

for employee in employees:

pickle.dump(employee, file)

def main():

create_employee_file()
display_employees()

new_employee = {'ecode': 'E004', 'ename': 'David', 'designation': 'Operator', 'salary':


3500}

insert_employee(new_employee)

print("\nAfter inserting new employee:")

display_employees()

if __name__ == "__main__":

main()

import pickle

import os

def create_employee_file():

employees = [

{'ecode': 'E001', 'ename': 'Alice', 'designation': 'Manager', 'salary': 5000},

{'ecode': 'E002', 'ename': 'Bob', 'designation': 'Operator', 'salary': 3000},

{'ecode': 'E003', 'ename': 'Charlie', 'designation': 'Manager', 'salary': 6000}

with open("employees.dat", "wb") as file:

for employee in employees:

pickle.dump(employee, file)

def display_employees():
print("Employee Records:")

with open("employees.dat", "rb") as file:

try:

while True:

employee = pickle.load(file)

print(employee)

except EOFError:

pass

def insert_employee(new_employee):

employees = []

with open("employees.dat", "rb") as file:

try:

while True:

employee = pickle.load(file)

employees.append(employee)

except EOFError:

pass

employees.append(new_employee)

employees.sort(key=lambda x: x['ecode'])

with open("employees.dat", "wb") as file:

for employee in employees:

pickle.dump(employee, file)
def main():

create_employee_file()

display_employees()

new_employee = {'ecode': 'E004', 'ename': 'David', 'designation': 'Operator', 'salary':


3500}

insert_employee(new_employee)

print("\nAfter inserting new employee:")

display_employees()

if __name__ == "__main__":

main()

Output:

17.Write a random number generator that generates random numbers between 1 and 6 (simulates
a dice).

Answer:

import random
def roll_dice():

return random.randint(1, 6)

def main():

number_of_rolls = int(input("Enter the number of dice rolls: "))

for _ in range(number_of_rolls):

print("You rolled:", roll_dice())

if __name__ == "__main__":

main()

Ouput:
18.

Answer:

1.

2.

19. Consider the following tables SCHOOL and answer this question :
Answer:

1.

2.

3.

4.
20.

Answer:

1.

2.

3.

4.
21. Consider the following tables Supplier and Consumer. Write SQL commands for the
statements (a) to (d).

(a) To display the C_ID, Supplier name, Supplier Address, Consumer Name and Consumer
Address for every Consumer

(b) To display Consumer details in ascending order of CName

(c) To display number of Consumers from each city

(d) To display the details of suppliers whose supplier city is ‘Panjim’

Answer:

1.

2.
3.

4.

22. Write the outputs of the SQL queries (i) to (iv) based on the relations Drink and Consumer
given below:

(i) SELECT count(DISTINCT Address) FROM Consumer;

(ii) SELECT Company, MAX(Price), MIN(Price), COUNT(*) from Drink GROUP BY


Company;

(iii) SELECT Consumer.ConsumerName, Drink.DrinkName, Drink.Price FROM Drink,


Consumer WHERE Consumer.D_ID = Drink.D_ID;

(iv) SELECT DrinkName from Drink where DrinkName like “-a%”;

Answer:

1.

2
3.

4.

23. Write SQL commands for the queries (i) to (iv) based on a table COMPANY
andCUSTOMER

1. To display those company name which are having prize less than 30000.

2. To display the name of the companies in reverse alphabetical order.

3. To increase the prize by 1000 for those customer whose name starts with ‘S’?

4. To add one more column totalprice with decimal(10,2) to the table customer

Answer:

1.
2.

3.

4.

24. Write a menu driven program using functions to implement all the stack operations?

(STNO, STNAME, GENDER, MARKS, )

Answer:

stack = []
def push():

stno = input("Enter student number (STNO): ")

stname = input("Enter student name (STNAME): ")

gender = input("Enter gender: ")

marks = float(input("Enter marks: "))

student = {'STNO': stno, 'STNAME': stname, 'GENDER': gender, 'MARKS': marks}

stack.append(student)

print(f"Student {stname} added to stack.\n")

def pop():

if not stack:

print("Stack is empty. No student to remove.\n")

else:

student = stack.pop()

print(f"Removed student: {student['STNAME']}\n")

def peek():

if not stack:

print("Stack is empty.\n")

else:

student = stack[-1]

print(f"Top student in stack: {student}\n")

def display():

if not stack:
print("Stack is empty.\n")

else:

print("Stack contents:")

for student in reversed(stack):

print(student)

print()

def menu():

while True:

print("1. Push\n2. Pop\n3. Peek\n4. Display\n5. Exit")

choice = int(input("Enter your choice: "))

if choice == 1:

push()

elif choice == 2:

pop()

elif choice == 3:

peek()

elif choice == 4:

display()

elif choice == 5:

break

else:

print("Invalid choice.\n")

if __name__ == "__main__":
menu()

Output:
25. Vignesh has created a dictionary “employee” with employee name as key and their salary as
values. Write a program to perform the following operations in Python: (a) Push the names of
those employees into a stack where the salary is less than 50000 (b) Pop the elements of the stack
and display those names.

Answer:
Output:
26. Harsha has created a list 'mylist' of 10 integers. You have to help him to create a stack by
performing the following functions in Python: (a) Traverse each element of the list and push all
those numbers into the stack which are divisible by 3. (b) Pop from the stack and display all the
content

Answer:
Output:
27.. Write Python connectivity program to

1. create the table SALESMAN in SALES database

· Code

· Sales Man Name

· Address

· Commission

· Salary

2. Retrieve all the data from a table SALESMAN


3. Delete all the records from SALESMAN table whose SALARY >6000

Answer:

import sqlite3

# Connect to the database

conn = sqlite3.connect('SALES.db')

cursor = conn.cursor()

# 1. Create the SALESMAN table

def create_table():

cursor.execute('''CREATE TABLE IF NOT EXISTS SALESMAN (

Code TEXT PRIMARY KEY,

SalesManName TEXT,

Address TEXT,

Commission REAL,

Salary REAL)''')

conn.commit()

print("Table SALESMAN created successfully.\n")

# 2. Retrieve all the data from SALESMAN table

def retrieve_data():

cursor.execute("SELECT * FROM SALESMAN")

rows = cursor.fetchall()

print("Data from SALESMAN table:")

for row in rows:

print(row)
print()

# 3. Delete all records where Salary > 6000

def delete_records():

cursor.execute("DELETE FROM SALESMAN WHERE Salary > 6000")

conn.commit()

print("Records with Salary > 6000 deleted successfully.\n")

# Insert data to test the functionality

def insert_data():

data = [

('001', 'John Doe', '123 Elm Street', 10.5, 5500),

('002', 'Jane Smith', '456 Oak Avenue', 12.0, 6200),

('003', 'Bob Brown', '789 Pine Road', 9.0, 5800)

cursor.executemany("INSERT INTO SALESMAN (Code, SalesManName, Address,


Commission, Salary) VALUES (?, ?, ?, ?, ?)", data)

conn.commit()

print("Sample data inserted successfully.\n")

def menu():

create_table()

insert_data()

retrieve_data()

Output:
28. Write a menu driven program to demonstrate four major operations using my SQL
connectivity

Create a Table STUDENT with (rollno,name,marks,city,Age)

· Add

· Update

· delete

· display

Answer:

import mysql.connector

# Establish a connection to MySQL database

conn = mysql.connector.connect(

host="localhost", # Update with your MySQL host

user="root", # Update with your MySQL user


password="", # Update with your MySQL password

database="school" # Create or use the database named 'school'

cursor = conn.cursor()

# 1. Create the STUDENT table

def create_table():

cursor.execute('''CREATE TABLE IF NOT EXISTS STUDENT (

rollno INT PRIMARY KEY,

name VARCHAR(100),

marks FLOAT,

city VARCHAR(100),

age INT)''')

conn.commit()

print("Table STUDENT created successfully.\n")

# 2. Add a new record to the STUDENT table

def add_student():

rollno = int(input("Enter Roll No: "))

name = input("Enter Name: ")

marks = float(input("Enter Marks: "))

city = input("Enter City: ")

age = int(input("Enter Age: "))

cursor.execute("INSERT INTO STUDENT (rollno, name, marks, city, age) VALUES


(%s, %s, %s, %s, %s)",
(rollno, name,

Output :
29. 29. Write a program to demonstrate fetchone(), fetchall(), fetchmany()and rowcount using
SQL connectivity .Create a table TEACHERS (ID,NAME,SUBJECT,CLASS)

Answer:

Output:
30. A public school is Managing Student data in STUDENT table in SCHOOL database, write a
python code that connects to database school and retrieves . all records and displays total number
of students

Answer:

import mysql.connector

# Connect to the MySQL database

conn = mysql.connector.connect(

host="localhost", # Update with your MySQL host

user="root", # Update with your MySQL user

password="", # Update with your MySQL password

database="school" # Database name

cursor = conn.cursor()

# Function to retrieve all student records and display the total number of students

def retrieve_students():

cursor.execute("SELECT * FROM STUDENT")

students = cursor.fetchall() # Fetch all records

total_students = cursor.rowcount # Get the total number of records

# Display all student records

print("Student Records:")

for student in students:


print(student)

# Display total number of students

print(f"\nTotal Number of Students: {total_students}")

# Call the function

retrieve_students()

# Close the connection

cursor.close()

conn.close()

import mysql.connector

# Connect to the MySQL database

conn = mysql.connector.connect(

host="localhost", # Update with your MySQL host

user="root", # Update with your MySQL user

password="", # Update with your MySQL password

database="school" # Database name

cursor = conn.cursor()

# Function to retrieve all student records and display the total number of students

def retrieve_students():

cursor.execute("SELECT * FROM STUDENT")


students = cursor.fetchall() # Fetch all records

total_students = cursor.rowcount # Get the total number of records

# Display all student records

print("Student Records:")

for student in students:

print(student)

# Display total number of students

print(f"\nTotal Number of Students: {total_students}")

# Call the function

retrieve_students()

# Close the connection

cursor.close()

conn.close()

Output:

You might also like