CS PRACTICAL FILE 2024 2025 (1) .Document
CS PRACTICAL FILE 2024 2025 (1) .Document
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
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
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: "))
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]
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}")
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
Select command
Insert command
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()