Akshat Sethi Practical File
Akshat Sethi Practical File
Practical File
Session 2024-25
Submitted by
Name: Akshat Sethi
Class Sec: 12th- B
Subject Teacher: Anshu Sharma
Roll No ________
INDEX
Python
Functions Programs:-
Python Code:-
def count_vowels_consonants(s):
vowels_count = 0
consonants_count = 0
vowels = 'aeiouAEIOU'
for char in s:
if char.isalpha():
if char in vowels:
vowels_count += 1
else:
consonants_count += 1
# Example usage
print(f"Vowels: {vowels}")
print(f"Consonants: {consonants}")
Output:
# Python program to sum all the positive and negative numbers in a
list.
Python code:-
def sum_positive_negative(numbers):
positive_sum = 0
negative_sum = 0
if num > 0:
positive_sum += num
else:
negative_sum += num
# Example usage
Output:
#Python Program Fibonacci Sequence using recursion
Python Code:-
def fibonacci(n):
# Base cases
if n == 0:
return 0
elif n == 1:
return 1
else:
print(fibonacci(6)) # Output: 8
Output:
# Python program to calculate sum and product of the first N numbers using a
loop.
Python Code:-
def calculate_sum_and_product(n):
total_sum = 0
total_product = 1
total_sum += num
total_product *= num
# Example usage
n = 10
Output:-
Python Program to Search for a Key in an In-Memory Dictionary
Python Code:-
employee_dict = {
def search_employee(emp_id):
if emp_id in employee_dict:
else:
# Example usage
Output:-
Data File Handling
Search the given word in the text file and display its occurrences and position
import os
def is_vowel(char):
def process_file(filename):
if not os.path.isfile(filename):
return
content = file.read()
# Initialize counters
total_characters = len(content)
total_words = len(words)
me_count = content.lower().count('me')
my_count = content.lower().count('my')
new_file.write(content)
# Search for a given word and display its occurrences and positions
def search_word(word):
occurrences = content.lower().count(word.lower())
positions = []
start = 0
while True:
if start == -1:
break
positions.append(start)
start += len(word)
words_in_line = len(line.split())
print(f"Digits: {digit_count}")
print(content_replaced)
# Example usage
filename = 'story.txt'
process_file(filename)
Output:-
Program to Count Sentences and Display Sentences with Exactly 10
Words
Python Code:
def process_file(filename):
try:
content = file.read()
total_sentences = len(sentences)
print(sentence)
except FileNotFoundError:
except Exception as e:
process_file('data.txt')
Output:
Binary File Programs:-
Python Code:
import pickle
import os
pickle.dump(data_list, file)
def read_list_from_file(filename):
if not os.path.exists(filename):
try:
data_list = pickle.load(file)
return data_list
except EOFError:
print("File is empty.")
def display_list(data_list):
if not data_list:
else:
if movie['title'].lower() == title.lower():
return
old_movie = data_list[index]
data_list[index] = new_movie
else:
print("Invalid index.")
del_movie = data_list.pop(index)
else:
print("Invalid index.")
def menu_list():
filename = 'movies_data.bin'
data_list = read_list_from_file(filename)
while True:
print("\nMenu:")
print("6. Exit")
if choice == '1':
write_list_to_file(filename, data_list)
display_list(data_list)
display_list(data_list)
try:
delete_item_from_list(data_list, index)
write_list_to_file(filename, data_list)
except ValueError:
search_item_in_list(data_list, title)
display_list(data_list)
try:
index = int(input("Enter the index of the movie to update: ").strip()) - 1
write_list_to_file(filename, data_list)
else:
print("Invalid index.")
except ValueError:
print("Exiting program.")
break
else:
if __name__ == "__main__":
menu_list()
Output:
#File Content for Dictionary Operations: dict_operations.py
Python Code:
# student_management.py
import pickle
import os
def initialize_student_file(filename):
"""Initialize the student binary file with sample data if it doesn't exist."""
if not os.path.isfile(filename):
sample_students = {
pickle.dump(sample_students, file)
print(f"Student binary file '{filename}' created and initialized with sample data.")
pickle.dump(student_dict, file)
def read_students_from_file(filename):
try:
student_dict = pickle.load(file)
return student_dict
except FileNotFoundError:
return {}
except EOFError:
return {}
def display_students(student_dict):
if not student_dict:
else:
print("\nStudent Details:")
if student_id in student_dict:
student = student_dict[student_id]
else:
def menu_student():
filename = 'student_data.bin'
initialize_student_file(filename)
student_dict = read_students_from_file(filename)
while True:
print("\nMenu:")
print("5. Exit")
if choice == '1':
write_students_to_file(filename, student_dict)
display_students(student_dict)
if student_id in student_dict:
del student_dict[student_id]
write_students_to_file(filename, student_dict)
else:
search_student_by_id(student_dict, student_id)
print("Exiting program.")
break
else:
if __name__ == "__main__":
menu_student
Output:
C.S.V File Programs:
Python Code:
# library_management.py
import csv
import os
def initialize_csv_file(filename):
"""Initialize the CSV file with sample book data if it doesn't exist."""
if not os.path.isfile(filename):
writer = csv.writer(file)
print(f"CSV file '{filename}' created and initialized with sample book data.")
def display_csv(filename):
if not os.path.isfile(filename):
return
reader = csv.reader(file)
print(", ".join(row))
def add_record(filename):
writer = csv.writer(file)
def search_record(filename):
found = False
reader = csv.reader(file)
if row[0] == id_to_search:
print(", ".join(row))
found = True
break
if not found:
def menu_csv():
filename = 'library.csv'
initialize_csv_file(filename)
while True:
print("\nLibrary Menu:")
print("4. Exit")
if choice == '1':
display_csv(filename)
add_record(filename)
search_record(filename)
print("Exiting program.")
break
else:
if __name__ == "__main__":
menu_csv()
Output:
MYSQL: - SINGLE TABLE BASED-1
# Do SQL Queries Consider the following table:
vi) Display all records where prize money is less than 10000.
SINGLE TABLE BASED- 2
ii.) Write a query to select the total sum of Amount, grouped by transaction
Type, from the TRANSACTION table.
iii.)Write a query to select the customer name (Cname), transaction date (Tdate),
and transaction amount (Amount) from the CUSTOMER and TRANSACTION
tables where the account numbers match (C.ACNO = T.ACNO) and the transaction
type is 'CREDIT'.
TWO TABLE BASED – 2
Tables: CARDEN and CUSTOMER:
(ii) Display name of car, make, and capacity of cars in descending order of
their sitting capacity.
(iii) Display the highest charges at which a vehicle can be hired from
CARDEN.
(iv) Display the customer name and the corresponding name of the cars hired by them.
Output:
Natural Join:
FROM CARDEN NATURAL JOINING CUSTOMER;
Output:
PYTHON AND SQL CONNECTIVITY Program:-
#Python and Sql Connectivity menu driven program
Python Code:
import mysql.connector
def connect_to_db():
try:
connection = mysql.connector.connect(
host='localhost',
user='root',
if connection.is_connected():
return connection
except Error as e:
print(f"Error: {e}")
return None
def create_database_and_table(connection):
try:
cursor = connection.cursor()
cursor.execute("USE account_db")
cursor.execute("""
""")
except Error as e:
print(f"Error: {e}")
def create_sample_data(cursor):
sample_accounts = [
try:
cursor.executemany("INSERT INTO accounts (username, email, password) VALUES (%s, %s, %s)",
sample_accounts)
except Error as e:
print(f"Error: {e}")
def create_account(cursor):
try:
cursor.execute("INSERT INTO accounts (username, email, password) VALUES (%s, %s, %s)",
print(f"Error: {e}")
def read_accounts(cursor):
try:
rows = cursor.fetchall()
print("\nAll Accounts:")
except Error as e:
print(f"Error: {e}")
def read_selected_account(cursor):
try:
row = cursor.fetchone()
if row:
else:
except Error as e:
print(f"Error: {e}")
def update_account(cursor):
try:
cursor.execute("UPDATE accounts SET username = %s, email = %s, password = %s WHERE id = %s",
except Error as e:
print(f"Error: {e}")
def delete_account(cursor):
try:
except Error as e:
print(f"Error: {e}")
def main():
connection = connect_to_db()
if connection is None:
return
create_database_and_table(connection)
cursor = connection.cursor()
create_sample_data(cursor)
connection.commit()
while True:
print("\nMenu:")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
create_account(cursor)
connection.commit()
read_accounts(cursor)
read_selected_account(cursor)
update_account(cursor)
connection.commit()
delete_account(cursor)
connection.commit()
print("Exiting...")
break
else:
cursor.close()
connection.close()
if __name__ == "__main__":
main()
Output:-