0% found this document useful (0 votes)
10 views37 pages

CS PRACTICAL FILE 2024 2025 (1) .Document

The document is a practical file for Class 12 students at Kendriya Vidyalaya for the academic year 2024-25, submitted by Rudra Pratap. It includes a list of programming tasks and projects covering topics such as data structures, file handling, sorting algorithms, and interest calculations using Python. Each task is accompanied by sample code and expected outputs, demonstrating the implementation of various programming concepts.
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)
10 views37 pages

CS PRACTICAL FILE 2024 2025 (1) .Document

The document is a practical file for Class 12 students at Kendriya Vidyalaya for the academic year 2024-25, submitted by Rudra Pratap. It includes a list of programming tasks and projects covering topics such as data structures, file handling, sorting algorithms, and interest calculations using Python. Each task is accompanied by sample code and expected outputs, demonstrating the implementation of various programming concepts.
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/ 37

ACADEMIC YEAR: 2024-25 KENDRIYA VIDYALAYA-110022

SECTOR-8 RK PURAM ND

CLASS 12
PRACTICAL FILE
SUBMITTED BY: RUDRA PRATAP
SUBMITTED TO: MS. KRITIKA
CLASS:12A
ROLL NO.:18
LIST OF PRACTICALS -CLASS XII -SESSION 2024-25

SR NO TITLE OF PROGRAM DATE SIGN


REVISION TOUR
1 To create a dictionary to store names and phone
numbers of 5 friends by accepting inputs from user
and perform search by key and modification of
phone no of a friend.
2 To develop a quiz. Store any 10 questions and
answers. Randomly select questions and print a
score card for user.
3 To implement 3 sorting techniques i) Bubble Sort
ii) Selection sort iii) Insertion sort using python list
FUNCTIONS
4 To Write a menu driven program to calculate
volumes and surface area of sphere and cuboid
.Program will contain different user defined
functions to calculate area and volumes
5 To write a menu driven program to calculate
simple interest and compound interest .Program
will give default values for rate of interest
TEXT FILE HANDLING
6 To create a text file and write some text into it.
Write a menu driven program to calculate i) no of
words in the file ii) To display longest line in the
file iii) T calculate no of lines starting with “The”.
Consider all case variants of “The”
7 To create a text file and write some text into it.
Write a menu driven program i) To calculate no of
digits in a file ii) To count no of times “me” or
“my” occurs in the file .(Consider all case variants
of
“me” or “my”)
BINARY FILE HANDLING
8 Write a menu driven program to do the following
1. To create a binary file and write records of
employee emp id ,emp name and salary.
2. . To search by emp name and display the record.
3. To change salary of a particular employee
4. To delete a record who has left the job
CSV FILE HANDLING
9 Write a menu driven program to do the following
1. To create a csv file and write records of students
records [adm no,name,percentage]
2. To search by name and display the record
3. To modify percentage of student.
4. To count no of records whose percentage is
above 90
STACK IMPLEMENTATION
10 Implement stack as per requirement given below
1. A List contains records as list elements
[ City,Country,distance from Delhi]
2. Write Push( lst) which takes the nested list
as argument and pushes a list object
containing name of city and country
,which are not in India distance is less than
3500 km from Delhi
3. Pop() To pop the objects from stack and
displays them , Also the function should
display appropriate message when stack is
empty

11 Implement stack as per requirement given below


Create a dictionary of kitchen items –{Item:price}
1. A function to push the items on stack
whose price is less than 100.Also
display average price of elements
pushed onto stack
2 A function to pop the objects from stack
and displays them , Also the function
should display appropriate message when
stack is empty

MYSQL
12 Simple queries
13 Queries based on aggregate functions
14 Queries based on joins
15 Queries based on group by clause
Python and mysql connectivity
16 Select command
17 Insert command
18 Update and delete command

1. To create a dictionary to store names and phone numbers of 5 friends by accepting


inputs from user and perform search by key and modification of phone number of a
friend.
def create_friends_dict():
friends_dict = {}
for i in range(5):
name = input(f"Enter the name of friend {i+1}: ")
phone_number = input(f"Enter the phone number of {name}: ")
friends_dict[name] = phone_number
return friends_dict
def search_friend(friends_dict):
search_name = input("Enter the name of the friend to search for: ")
if search_name in friends_dict:
print(f"{search_name}'s phone number is: {friends_dict[search_name]}")
else:
print(f"{search_name} is not found in the contact list.")
def modify_phone_number(friends_dict):
modify_name = input("Enter the name of the friend whose phone number you want to
modify: ")
if modify_name in friends_dict:
new_phone_number = input(f"Enter the new phone number for {modify_name}: ")
friends_dict[modify_name] = new_phone_number
print(f"Phone number for {modify_name} has been updated.")
else:
print(f"{modify_name} is not found in the contact list.")
def main():
friends_dict = create_friends_dict()
while True:
print("\nMenu:")
print("1. Search by friend's name")
print("2. Modify friend's phone number")
print("3. Exit")
choice = input("Enter your choice: ")
if choice == '1':
search_friend(friends_dict)
elif choice == '2':
modify_phone_number(friends_dict)
elif choice == '3':
print("Exiting the program.")
break
else:
print("Invalid choice! Please choose a valid option.")

main()
OUTPUT
Enter the name of friend 1: Azad
Enter the phone number of Azad: 1234567890
Enter the name of friend 2: Azad
Enter the phone number of Azad: 9876543210
Enter the name of friend 3: Bhaskar
Enter the phone number of Bhaskar:55555555
Enter the name of friend 4: Chirag
Enter the phone number of Chirag:4444444
Enter the name of friend 5: Abhinav
Enter the phone number of Abhinav: 3333333333
Menu:
1. Search by friend's name
2. Modify friend's phone number
3. Exit
Enter your choice: 1
Enter the name of the friend to search for: Azad
Azad’s phone number is: 9876543210
Menu:
1. Search by friend's name
2. Modify friend's phone number
3. Exit
Enter your choice: 2
Enter the name of the friend whose phone number you want to modify: Bhaskar
Enter the new phone number for Bhaskar: 6666666666
Phone number for Bhaskar has been updated.
Menu:
1. Search by friend's name
2. Modify friend's phone number
3. Exit
Enter your choice: 3
Exiting the program.
2. To develop a quiz. Store any 10 questions and
answers. Randomly select questions and print a score card for user.
def create_quiz():
quiz_questions =
{"What is the capital of France?": "Paris",
"Who is the author of '1984'?": "George Orwell",
"What is the atomic number of Carbon?": "6",
"What is the chemical formula of water?": "H2O",
"Who invented the light bulb?": "Thomas Edison",
"What is the speed of light in a vacuum (m/s)?": "3x10^8",
"Who developed the theory of relativity?": "Albert Einstein",
"What is the longest river in the world?": "Nile",
"Who wrote the play 'Romeo and Juliet'?": "William Shakespeare",
"What is the SI unit of force?": "Newton"}
return quiz_questions
def conduct_quiz():
quiz_questions = create_quiz()
score = 0
total_questions = len(quiz_questions)
question_keys =
["What is the capital of France?",
"Who is the author of '1984'?",
"What is the atomic number of Carbon?",
"What is the chemical formula of water?",
"Who invented the light bulb?",
"What is the speed of light in a vacuum (m/s)?",
"Who developed the theory of relativity?",
"What is the longest river in the world?",
"Who wrote the play 'Romeo and Juliet'?",
"What is the SI unit of force?"]
print("Welcome to the Class 12 Quiz! Please answer the following questions:\n")
for question in question_keys:
correct_answer = quiz_questions[question]
print(f"Question: {question}")
user_answer = input("Your answer: ")
if user_answer.lower() == correct_answer.lower():
print("Correct!\n")
score += 1
else:
print(f"Wrong! The correct answer is: {correct_answer}\n")

print("\nQuiz Over!")
print(f"Your final score: {score}/{total_questions}")
if score == total_questions:
print("Excellent! You got all correct.")
elif score >= total_questions // 2:
print("Good job! Keep practicing.")
else:
print("Better luck next time. Keep studying!")
OUTPUT
Welcome to the Class 12 Quiz! Please answer the following questions:
Question: What is the capital of France?
Your answer: Paris
Correct!
Question: Who is the author of '1984'?
Your answer: George Orwell
Correct!
Question: What is the atomic number of Carbon?
Your answer: 6
Correct!
Question: What is the chemical formula of water?
Your answer: H2O
Correct!
Question: Who invented the light bulb?
Your answer: Thomas Edison
Correct!
Question: What is the speed of light in a vacuum (m/s)?
Your answer: 3x10^8
Correct!
Question: Who developed the theory of relativity?
Your answer: Albert Einstein
Correct!
Question: What is the longest river in the world?
Your answer: Nile
Correct!
Question: Who wrote the play 'Romeo and Juliet'?
Your answer: William Shakespeare
Correct!
Question: What is the SI unit of force?
Your answer: Newton
Correct!
Quiz Over!
Your final score: 10/10
Excellent! You got all correct.
3.To implement 3 sorting techniques i) Bubble Sort
ii) Selection sort iii) Insertion sort using python list.
def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
return arr
def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i+1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
return arr
def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i-1
while j >= 0 and arr[j] > key:
arr[j+1] = arr[j]
j -= 1
arr[j+1] = key
return arr
def main():
arr = [64, 25, 12, 22, 11]
print("Original Array:", arr)
print("\nBubble Sort:")
bubble_sorted_arr = arr
bubble_sort(bubble_sorted_arr)
print("Sorted Array:", bubble_sorted_arr)
arr = [64, 25, 12, 22, 11]
print("\nSelection Sort:")
selection_sorted_arr = arr
selection_sort(selection_sorted_arr)
print("Sorted Array:", selection_sorted_arr)
arr = [64, 25, 12, 22, 11]
print("\nInsertion Sort:")
insertion_sorted_arr = arr
insertion_sort(insertion_sorted_arr)
print("Sorted Array:", insertion_sorted_arr)
main()
OUTPUT
Original Array: [64, 25, 12, 22, 11]
Bubble Sort:
Sorted Array: [11, 12, 22, 25, 64]
Selection Sort:
Sorted Array: [11, 12, 22, 25, 64]
Insertion Sort:
Sorted Array: [11, 12, 22, 25, 64]
4. To Write a menu driven program to calculate volumes and surface area of sphere and
cuboid.Program will contain different user defined functions to calculate area and volumes.
def sphere_volume(radius):
pi = 3.14 # Using 3.14 for Pi
volume = (4/3) * pi * (radius**3)
return volume
def sphere_surface_area(radius):
pi = 3.14 # Using 3.14 for Pi
surface_area = 4 * pi * (radius**2)
return surface_area
def cuboid_volume(length, width, height):
volume = length * width * height
return volume
def cuboid_surface_area(length, width, height):
surface_area = 2 * (length*width + width*height + height*length)
return surface_area
def main():
while True:
print("\nMenu:")
print("1. Calculate volume and surface area of a sphere")
print("2. Calculate volume and surface area of a cuboid")
print("3. Exit")
choice = input("Enter your choice (1/2/3): ")
if choice == '1':
radius = float(input("Enter the radius of the sphere: "))
print(f"Volume of the sphere: {sphere_volume(radius):.2f}")
print(f"Surface area of the sphere: {sphere_surface_area(radius):.2f}")
elif choice == '2':
length = float(input("Enter the length of the cuboid: "))
width = float(input("Enter the width of the cuboid: "))
height = float(input("Enter the height of the cuboid: "))
print(f"Volume of the cuboid: {cuboid_volume(length, width, height):.2f}")
print(f"Surface area of the cuboid: {cuboid_surface_area(length, width, height):.2f}")
elif choice == '3':
print("Exiting the program.")
break
else:
print("Invalid choice! Please select a valid option.")
main()
OUTPUT
Menu:
1. Calculate volume and surface area of a sphere
2. Calculate volume and surface area of a cuboid
3. Exit
Enter your choice (1/2/3): 1
Enter the radius of the sphere: 5
Volume of the sphere: 523.33
Surface area of the sphere: 314.00
Menu:
1. Calculate volume and surface area of a sphere
2. Calculate volume and surface area of a cuboid
3. Exit
Enter your choice (1/2/3): 2
Enter the length of the cuboid: 3
Enter the width of the cuboid: 4
Enter the height of the cuboid: 5
Volume of the cuboid: 60.00
Surface area of the cuboid: 94.00
Menu:
1. Calculate volume and surface area of a sphere
2. Calculate volume and surface area of a cuboid
3. Exit
Enter your choice (1/2/3): 3
Exiting the program.
5. To write a menu driven program to calculate simple interest and compound
interest .Program will give default values for rate of interest
def simple_interest(principal, rate, time):
interest = (principal * rate * time) / 100
return interest
def compound_interest(principal, rate, time):
amount = principal * (1 + rate / 100) ** time
interest = amount - principal
return interest
def main():
rate_of_interest = 5 # Default rate of interest (5%)
while True:
print("\nMenu:")
print("1. Calculate Simple Interest")
print("2. Calculate Compound Interest")
print("3. Exit")
choice = input("Enter your choice (1/2/3): ")
if choice == '1':
principal = float(input("Enter the principal amount: "))
time = float(input("Enter the time period (in years): "))
interest = simple_interest(principal, rate_of_interest, time)
print(f"Simple Interest: {interest:.2f}")
elif choice == '2':
principal = float(input("Enter the principal amount: "))
time = float(input("Enter the time period (in years): "))
interest = compound_interest(principal, rate_of_interest, time)
print(f"Compound Interest: {interest:.2f}")
elif choice == '3':
print("Exiting the program.")
break
else:
print("Invalid choice! Please select a valid option.")

main()
OUTPUT
Menu:
1. Calculate Simple Interest
2. Calculate Compound Interest
3. Exit
Enter your choice (1/2/3): 1
Enter the principal amount: 1000
Enter the time period (in years): 2
Simple Interest: 100.00
Menu:
1. Calculate Simple Interest
2. Calculate Compound Interest
3. Exit
Enter your choice (1/2/3): 2
Enter the principal amount: 1000
Enter the time period (in years): 2
Compound Interest: 102.50
Menu:
1. Calculate Simple Interest
2. Calculate Compound Interest
3. Exit
Enter your choice (1/2/3): 3
Exiting the program.
6. To create a text file and write some text into it. Write a menu driven program to calculate
i) no of words in the file
ii) To display longest line in the file
iii) T calculate no of lines starting with “The”.
Consider all case variants of “The”
def create_file():
with open("sample.txt", "w") as file:
file.write("""This is a sample text file.
The quick brown fox jumps over the lazy dog.
the sun rises in the east.
She said, "The world is beautiful."
The car is moving fast.””)
print("File created and text written successfully!")
def count_words_in_file():
with open("sample.txt", "r") as file:
text = file.read()
words = text.split()
return len(words)
def longest_line_in_file():
with open("sample.txt", "r") as file:
lines = file.readlines()
longest_line = ""
for line in lines:
if len(line) > len(longest_line):
longest_line = line
return longest_line
def count_lines_starting_with_the():
with open("sample.txt", "r") as file:
lines = file.readlines()
count = 0
for line in lines:
if len(line) > 3 and (line[0:3].lower() == "the"): # Check the first 3 characters
count += 1
return count
def main():
create_file() # Create and write text into the file
while True:
print("\nMenu:")
print("1. Calculate number of words in the file")
print("2. Display the longest line in the file")
print("3. Calculate the number of lines starting with 'The'")
print("4. Exit")
choice = input("Enter your choice (1/2/3/4): ")
if choice == '1':
word_count = count_words_in_file()
print(f"Number of words in the file: {word_count}")
elif choice == '2':
longest_line = longest_line_in_file()
print(f"Longest line in the file: {longest_line}")
elif choice == '3':
lines_count = count_lines_starting_with_the()
print(f"Number of lines starting with 'The': {lines_count}")
elif choice == '4':
print("Exiting the program.")
break
else:
print("Invalid choice! Please select a valid option.")
main()

OUTPUT
File created and text written successfully!
Menu:
1. Calculate number of words in the file
2. Display the longest line in the file
3. Calculate the number of lines starting with 'The'
4. Exit
Enter your choice (1/2/3/4): 1
Number of words in the file: 19
Menu:
1. Calculate number of words in the file
2. Display the longest line in the file
3. Calculate the number of lines starting with 'The'
4. Exit
Enter your choice (1/2/3/4): 2
Longest line in the file: She said, "The world is beautiful."
Menu:
1. Calculate number of words in the file
2. Display the longest line in the file
3. Calculate the number of lines starting with 'The'
4. Exit
Enter your choice (1/2/3/4): 3
Number of lines starting with 'The': 3
Menu:
1. Calculate number of words in the file
2. Display the longest line in the file
3. Calculate the number of lines starting with 'The'
4. Exit
Enter your choice (1/2/3/4): 4
Exiting the program.
7.To create a text file and write some text into it. Write a menu driven program i) To
calculate no of digits in a file ii) To count no of times “me” or “my” occurs in the file .
(Consider all case variants of “me” or “my”)
def create_file():
with open("sample.txt", "w") as file:
file.write("""This is a sample text file.
My name is John, and I love programming.
This file contains some text for testing purposes.
I want to see how many digits and words like 'me' and 'my' are present.
Me and my friends enjoy learning new things.””)
print("File created and text written successfully!")
def count_digits_in_file():
with open("sample.txt", "r") as file:
text = file.read()
digits = [char for char in text if char.isdigit
return len(digits)
def count_me_my_in_file():
with open("sample.txt", "r") as file:
text = file.read()
words = text.split()
count = 0
for word in words:
if word.lower() == "me" or word.lower() == "my":
count += 1
return count
def main():
create_file()
while True:
print("\nMenu:")
print("1. Calculate number of digits in the file")
print("2. Count the number of times 'me' or 'my' occurs in the file")
print("3. Exit")
choice = input("Enter your choice (1/2/3): ")
if choice == '1':
digit_count = count_digits_in_file()
print(f"Number of digits in the file: {digit_count}")
elif choice == '2':
me_my_count = count_me_my_in_file()
print(f"Number of occurrences of 'me' or 'my' in the file: {me_my_count}")
elif choice == '3':
print("Exiting the program.")
break
else:
print("Invalid choice! Please select a valid option.")
main()
OUTPUT
File created and text written successfully!
Menu:
1. Calculate number of digits in the file
2. Count the number of times 'me' or 'my' occurs in the file
3. Exit
Enter your choice (1/2/3): 1
Number of digits in the file: 6
Menu:
1. Calculate number of digits in the file
2. Count the number of times 'me' or 'my' occurs in the file
3. Exit
Enter your choice (1/2/3): 2
Number of occurrences of 'me' or 'my' in the file: 5
Menu:
1. Calculate number of digits in the file
2. Count the number of times 'me' or 'my' occurs in the file
3. Exit
Enter your choice (1/2/3): 3
Exiting the program.
8. Write a menu driven program to do the following
1. To create a binary file and write records of employee emp id ,emp name and
salary.
2. . To search by emp name and display the record.
3. To change salary of a particular employee
4. To delete a record who has left the job
import pickle
def create_file():
with open("employees.dat", "wb") as file:
while True:
emp_id = int(input("Enter employee ID: "))
emp_name = input("Enter employee name: ")
salary = float(input("Enter employee salary: "))

employee = {'emp_id': emp_id, 'emp_name': emp_name, 'salary': salary}


pickle.dump(employee, file)
more = input("Do you want to add another employee? (y/n): ")
if more.lower() != 'y':
break
print("Employee records have been saved to the binary file.")
def search_employee_by_name():
emp_name = input("Enter the employee name to search: ")
found = False
with open("employees.dat", "rb") as file:
while True:
try:
employee = pickle.load(file)
if employee['emp_name'].lower() == emp_name.lower():
print(f"Emp ID: {employee['emp_id']}, Emp Name: {employee['emp_name']},
Salary: {employee['salary']}")
found = True
break
except EOFError:
break
if not found:
print("Employee not found.")
def change_salary():
emp_name = input("Enter the employee name to change salary: ")
new_salary = float(input("Enter the new salary: "))
updated = False
employees = []
with open("employees.dat", "rb") as file:
while True:
try:
employee = pickle.load(file)
if employee['emp_name'].lower() == emp_name.lower():
employee['salary'] = new_salary
updated = True
employees.append(employee)
except EOFError:
break
if updated:
with open("employees.dat", "wb") as file:
for employee in employees:
pickle.dump(employee, file)
print(f"Salary of {emp_name} has been updated to {new_salary}.")
else:
print("Employee not found.")
def delete_employee():
emp_name = input("Enter the employee name to delete: ")
deleted = False
employees = []
with open("employees.dat", "rb") as file:
while True:
try:
employee = pickle.load(file)
if employee['emp_name'].lower() != emp_name.lower():
employees.append(employee)
else:
deleted = True
except EOFError:
break
if deleted:
with open("employees.dat", "wb") as file:
for employee in employees:
pickle.dump(employee, file)
print(f"Record of {emp_name} has been deleted.")
else:
print("Employee not found.")
def main():
while True:
print("\nMenu:")
print("1. Create a binary file and write employee records")
print("2. Search by employee name and display the record")
print("3. Change salary of a particular employee")
print("4. Delete the record of an employee who has left the job")
print("5. Exit")
choice = input("Enter your choice (1/2/3/4/5): ")
if choice == '1':
create_file()
elif choice == '2':
search_employee_by_name()
elif choice == '3':
change_salary()
elif choice == '4':
delete_employee()
elif choice == '5':
print("Exiting the program.")
break
else:
print("Invalid choice! Please select a valid option.")

main()
OUTPUT
Menu:
1. Create a binary file and write employee records
2. Search by employee name and display the record
3. Change salary of a particular employee
4. Delete the record of an employee who has left the job
5. Exit
Enter your choice (1/2/3/4/5): 1
Enter employee ID: 101
Enter employee name: John
Enter employee salary: 50000
Do you want to add another employee? (y/n): y
Enter employee ID: 102
Enter employee name: Alice
Enter employee salary: 60000
Do you want to add another employee? (y/n): n
Employee records have been saved to the binary file.
Menu:
1. Create a binary file and write employee records
2. Search by employee name and display the record
3. Change salary of a particular employee
4. Delete the record of an employee who has left the job
5. Exit
Enter your choice (1/2/3/4/5): 2
Enter the employee name to search: John
Emp ID: 101, Emp Name: John, Salary: 50000.0
Menu:
1. Create a binary file and write employee records
2. Search by employee name and display the record
3. Change salary of a particular employee
4. Delete the record of an employee who has left the job
5. Exit
Enter your choice (1/2/3/4/5): 3
Enter the employee name to change salary: Alice
Enter the new salary: 65000
Salary of Alice has been updated to 65000.0.
Menu:
1. Create a binary file and write employee records
2. Search by employee name and display the record
3. Change salary of a particular employee
4. Delete the record of an employee who has left the job
5. Exit
Enter your choice (1/2/3/4/5): 4
Enter the employee name to delete: John
Record of John has been deleted.
9. Write a menu driven program to do the following
1. To create a csv file and write records of students records [adm no,name,percentage]

2. To search by name and display the record

3. To modify percentage of student.

4. To count no of records whose percentage is

above 90
import csv
def create_csv_file():
with open('students.csv', mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerow(['Adm No', 'Name', 'Percentage'])
while True:
adm_no = input("Enter admission number: ")
name = input("Enter student name: ")
percentage = float(input("Enter student percentage: "))
writer.writerow([adm_no, name, percentage])
more = input("Do you want to add another record? (y/n): ")
if more.lower() != 'y':
break
print("Student records have been saved to the CSV file.")
def search_student_by_name():
name = input("Enter the name of the student to search: ")
found = False
with open('students.csv', mode='r') as file:
reader = csv.reader(file)
next(reader) # Skip the header row
for row in reader:
if row[1].lower() == name.lower():
print(f"Adm No: {row[0]}, Name: {row[1]}, Percentage: {row[2]}")
found = True
break
if not found:
print("Student not found.")
def modify_percentage():
name = input("Enter the name of the student to modify percentage: ")
new_percentage = float(input("Enter the new percentage: "))
updated = False
students = []
with open('students.csv', mode='r') as file:
reader = csv.reader(file)
header = next(reader)
students.append(header)
for row in reader:
if row[1].lower() == name.lower():
row[2] = str(new_percentage)
updated = True
students.append(row)
if updated:
with open('students.csv', mode='w', newline='') as file:
writer = csv.writer(file)
writer.writerows(students)
print(f"Percentage of {name} has been updated to {new_percentage}.")
else:
print("Student not found.")
def count_students_above_90():
count = 0
with open('students.csv', mode='r') as file:
reader = csv.reader(file)
next(reader) # Skip the header row
for row in reader:
if float(row[2]) > 90:
count += 1
print(f"Number of students with percentage above 90: {count}")
def main():
while True:
print("\nMenu:")
print("1. Create a CSV file and write student records")
print("2. Search by student name and display the record")
print("3. Modify the percentage of a student")
print("4. Count number of students with percentage above 90")
print("5. Exit")
choice = input("Enter your choice (1/2/3/4/5): ")
if choice == '1':
create_csv_file()
elif choice == '2':
search_student_by_name()
elif choice == '3':
modify_percentage()
elif choice == '4':
count_students_above_90()
elif choice == '5':
print("Exiting the program.")
break
else:
print("Invalid choice! Please select a valid option.")

main()
Menu:
1. Create a CSV file and write student records
2. Search by student name and display the record
3. Modify the percentage of a student
4. Count number of students with percentage above 90
5. Exit
Enter your choice (1/2/3/4/5): 1
Enter admission number: 101
Enter student name: John
Enter student percentage: 85
Do you want to add another record? (y/n): y
Enter admission number: 102
Enter student name: Alice
Enter student percentage: 92
Do you want to add another record? (y/n): n
Student records have been saved to the CSV file.
Menu:
1. Create a CSV file and write student records
2. Search by student name and display the record
3. Modify the percentage of a student
4. Count number of students with percentage above 90
5. Exit
Enter your choice (1/2/3/4/5): 2
Enter the name of the student to search: Alice
Adm No: 102, Name: Alice, Percentage: 92.0
Menu:
1. Create a CSV file and write student records
2. Search by student name and display the record
3. Modify the percentage of a student
4. Count number of students with percentage above 90
5. Exit
Enter your choice (1/2/3/4/5): 3
Enter the name of the student to modify percentage: John
Enter the new percentage: 88
Percentage of John has been updated to 88.0.
Menu:
1. Create a CSV file and write student records
2. Search by student name and display the record
3. Modify the percentage of a student
4. Count number of students with percentage above 90
5. Exit
Enter your choice (1/2/3/4/5): 4
Number of students with percentage above 90: 1
10. Implement stack as per requirement given below
1. A List contains records as list elements [ City,Country,distance from Delhi]
2. Write Push( lst) which takes the nested list as argument and pushes a list object
containing name of city and country ,which are not in India distance is less than
3500 km from Delhi
Pop() To pop the objects from stack and displays them , Also the function should display
appropriate message when stack is empty
stack = []
def Push(lst):
global stack
for record in lst:
city, country, distance = record
if country.lower() != 'india' and distance < 3500:
stack.append(record)
print(f"Pushed to stack: {record}")
else:
print(f"Skipping record: {record} (Either in India or distance is greater than 3500 km)")
def Pop():
global stack
if len(stack) == 0:
print("Stack is empty. No records to pop.")
else:
popped_record = stack.pop()
print(f"Popped from stack: {popped_record}")

# Sample records [City, Country, Distance from Delhi in km]


records =
[ ['Paris', 'France', 6000],
['New York', 'USA', 13000],
['Kabul', 'Afghanistan', 2500],
['Kathmandu', 'Nepal', 1000],
['Dhaka', 'Bangladesh', 1500],
['Beijing', 'China', 3500],
['London', 'UK', 7000]]
Push(records)
Pop()
Pop()
Pop()
Pop()
OUTPUT
Pushed to stack: ['Kabul', 'Afghanistan', 2500]
Pushed to stack: ['Kathmandu', 'Nepal', 1000]
Pushed to stack: ['Dhaka', 'Bangladesh', 1500]
Skipping record: ['Paris', 'France', 6000] (Either in India or distance is greater than 3500 km)
Skipping record: ['New York', 'USA', 13000] (Either in India or distance is greater than 3500
km)
Skipping record: ['Beijing', 'China', 3500] (Either in India or distance is greater than 3500 km)
Skipping record: ['London', 'UK', 7000] (Either in India or distance is greater than 3500 km)
Popped from stack: ['Dhaka', 'Bangladesh', 1500]
Popped from stack: ['Kathmandu', 'Nepal', 1000]
Popped from stack: ['Kabul', 'Afghanistan', 2500]
Stack is empty. No records to pop.
11. Implement stack as per requirement given below Create a dictionary of kitchen items –
{Item:price}
1. A function to push the items on stack whose price is less than 100.Also display
average price of elements pushed onto stack
2. A function to pop the objects from stack and displays them , Also the function
should display appropriate message when stack is empty
stack = []

kitchen_items ={ 'Spoon': 20, 'Plate': 50, 'Cup': 40, 'Fork': 30,'Glass': 60, 'Pan':
150,'Knife': 90, 'Grater': 80, 'Towel': 120, 'Mug': 40}
def Push():
global stack
total_price = 0
count = 0
item_list = list(kitchen_items)
for item in item_list:
price = kitchen_items[item]
if price < 100:
stack.append((item, price))
total_price += price
count += 1
print(f"Pushed to stack: {item} with price {price}")
if count > 0:
average_price = total_price / count
print(f"\nAverage price of items pushed onto stack: {average_price:.2f}")
else:
print("\nNo items were pushed to the stack as their prices were above 100.")
def Pop():
global stack
if len(stack) == 0:
print("\nStack is empty. No records to pop.")
else:
popped_item = stack.pop()
print(f"\nPopped from stack: {popped_item[0]} with price {popped_item[1]}")
Push()
Pop()
Pop()
Pop()

Pop()
OUTPUT
Pushed to stack: Spoon with price 20
Pushed to stack: Plate with price 50
Pushed to stack: Cup with price 40
Pushed to stack: Fork with price 30
Pushed to stack: Glass with price 60
Pushed to stack: Knife with price 90
Pushed to stack: Grater with price 80
Pushed to stack: Mug with price 40
Average price of items pushed onto stack: 47.14
Popped from stack: Mug with price 40
Popped from stack: Grater with price 80
Popped from stack: Knife with price 90
Stack is empty. No records to pop.

MYSQL
MYSQL

Simple queries

Queries based on aggregate functions


Queries based on joins

Queries based on group by clause

Python and mysql connectivity

Select command

Insert command

Update and delete command

SELECT * FROM students;


SELECT student_id, name, age FROM students;
SELECT * FROM students WHERE age > 18;
SELECT COUNT(*) FROM students;
SELECT AVG(age) FROM students;
SELECT MAX(grade) FROM students;
SELECT SUM(marks) FROM students;
SELECT students.name, courses.course_name
FROM students
INNER JOIN courses ON students.student_id = courses.student_id;
SELECT students.name, courses.course_name
FROM students
LEFT JOIN courses ON students.student_id = courses.student_id;
SELECT age, COUNT(*) AS num_students
FROM students
GROUP BY age;
SELECT course_id, AVG(grade) AS avg_grade
FROM students
GROUP BY course_id;
INTERFACE:
import mysql.connector
conn = mysql.connector.connect( host="localhost",user="root” password="1234 ",
database="DATABASE ")
cursor = conn.cursor()
cursor.execute("SELECT * FROM students")
results = cursor.fetchall()
for row in results:
print(row)
cursor.close()
conn.close()
SELECT * FROM students;
SELECT student_id, name, age FROM students;
INSERT INTO students (student_id, name, age, grade)
VALUES (1, 'John Doe', 20, 'A');
cursor = conn.cursor()

# Insert a new student record


cursor.execute(""" INSERT INTO students (student_id, name, age, grade)
VALUES (%s, %s, %s, %s)""", (1, 'John Doe', 20, 'A'))
conn.commit()
cursor.close()
UPDATE students
SET age = 21
WHERE student_id = 1;
DELETE FROM students
WHERE student_id = 1;

cursor = conn.cursor()
cursor.execute("""
UPDATE students
SET grade = 'B'
WHERE student_id = 1""")
conn.commit()
cursor.execute("""DELETE FROM students WHERE student_id = 1""")
conn.commit()
cursor.close()

You might also like