Ansh Tygai Practical File
Ansh Tygai Practical File
Practical File
Session 2024-25
Submitted by
Name: Ansh Tyagi
Class Sec: 12th- B
Subject Teacher: Anshu Sharma
Roll No ________
Index:
1. Function
#write a python function that accepts a string and calculate the numer of uppercase and lower
case letters
Python Code:
def count_case_letters(s):
uppercase_count = 0
lowercase_count = 0
for char in s:
if char.isupper():
uppercase_count += 1
elif char.islower():
lowercase_count += 1
# Example usage
string = "Python programminG"
upper, lower = count_case_letters(string)
print(f"Uppercase letters: {upper}")
print(f"Lowercase letters: {lower}")
Output:
# writes a python function that accepts listing has parameter and return the sum of all the even no.
and odd no.
Python Code:
def sum_even_odd(numbers):
even_sum = 0
odd_sum = 0
if num % 2 == 0:
even_sum += num
else:
odd_sum += num
# Example usage
numbers_list = [1, 2, 3, 4, 5, 6]
ouput:
# write a python function to find the maximum of three numbers using recursion
Python code:
def max_of_two(x,y):
if x>y:
return x
return y
def max_if_threee(x,y,z):
return max_of_two(x,max_of_two(y,z))
print(max_of_three(8,-4,10))
Output:
# writes a python program to demonstrate the concept of variable length argument to calculate sum
and product of the first 10 numbers
Python code:-
def calculate_sum_and_product(*args):
total_sum = sum(args)
total_product = 1
total_product *= num
Output:
#write a user-defined function findname(name) where name is an argument in python to delete
phone number from a dictionary phonebook on the basis of the name,where name is paras
Python Code:
def findname(name):
if name in phonebook:
del phonebook[name]
else:
# Inform the user if the name does not exist in the phonebook
phonebook = {
"chairag": "234-567-8901",
"paras": "345-678-9012"
findname("paras")
# Print the updated phonebook
Output:
2. Data File handling
Search the given word in the text file and display its occurrences and position
Python code:
import string
content = file.read()
lines = file.readlines()
total_lines = len(lines)
total_words = len(content.split())
me_count = content.lower().split().count('me')
my_count = content.lower().split().count('my')
vowels = 'aeiou'
consonants_count = sum(1 for char in content.lower() if char in string.ascii_lowercase and char not
in vowels)
new_file.write(content)
. Search the given word in the text file and display its occurrences and positions
def search_word(word):
word_positions = []
index = content.lower().find(word.lower())
word_positions.append(index)
print(f"Digits: {digits_count}")
Python Code:
def process_file(filename):
try:
content = file.read()
words = content.split()
total_words = len(words)
print(word)
except FileNotFoundError:
except Exception as e:
process_file('letter.txt')
Output:
Binary File Programs:
Python code:
import pickle
import os
def initialize_dict_file(filename):
"""Initialize the dictionary binary file with sample data if it doesn't exist."""
if not os.path.isfile(filename):
sample_dict = {
"name": "Alice",
"age": "30",
"city": "Wonderland"
write_dict_to_file(filename, sample_dict)
print(f"Dictionary binary file '{filename}' created and initialized with sample data.")
pickle.dump(data_dict, file)
def read_dict_from_file(filename):
data_dict = pickle.load(file)
return data_dict
except FileNotFoundError:
return {}
except EOFError:
return {}
def display_dict(data_dict):
if not data_dict:
else:
print("\nDictionary Contents:")
print(f"{key}: {value}")
"""Searches for a key in the dictionary and displays its value if found."""
if key in data_dict:
else:
if key in data_dict:
del data_dict[key]
else:
def menu_dict():
filename = 'dict_data.bin'
initialize_dict_file(filename)
data_dict = read_dict_from_file(filename)
while True:
print("\nMenu:")
print("5. Exit")
if choice == '1':
data_dict[key] = value
write_dict_to_file(filename, data_dict)
display_dict(data_dict)
delete_key_in_dict(data_dict, key)
write_dict_to_file(filename, data_dict)
search_key_in_dict(data_dict, key)
print("Exiting program.")
break
else:
if __name__ == "__main__":
menu_dict()
Output:
#Menu-Driven Program for List Operations on a Binary File
Python code:
import pickle
pickle.dump(data_list, file)
def read_list_from_file(filename):
try:
data_list = pickle.load(file)
return data_list
except FileNotFoundError:
return []
except EOFError:
print("File is empty.")
return []
def display_list(data_list):
if not data_list:
print("\nList Contents:")
print(f"{i}. {item}")
"""Searches for an item in the list and displays its index if found."""
if item in data_list:
index = data_list.index(item)
else:
old_item = data_list[index]
data_list[index] = new_item
else:
print("Invalid index.")
del_item = data_list.pop(index)
print("Invalid index.")
def menu_list():
filename = 'list_data.bin'
data_list = read_list_from_file(filename)
while True:
print("\nMenu:")
print("6. Exit")
if choice == '1':
data_list.append(item)
write_list_to_file(filename, data_list)
display_list(data_list)
elif choice == '3':
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, item)
display_list(data_list)
try:
write_list_to_file(filename, data_list)
else:
print("Invalid index.")
except ValueError:
elif choice ==
print("Exiting program.")
break
else:
if __name__ == "__main__":
menu_list()
Output:
C.S.V File program
# # C. S.V file program Menu Driven don't add update and delete:
Python code:
import csv
import os
def initialize_csv_file(filename):
if not os.path.isfile(filename):
sample_data = [
writer = csv.writer(file)
writer.writerows(sample_data)
def read_csv_file(filename):
try:
data = list(reader)
return data
except FileNotFoundError:
return []
except Exception as e:
return []
writer = csv.writer(file)
writer.writerows(data)
def display_csv_content(data):
if not data:
else:
return
def add_record_to_csv(filename):
data = read_csv_file(filename)
data.append(new_record)
write_csv_file(filename, data)
def menu_csv():
filename = 'data.csv'
initialize_csv_file(filename)
while True:
data = read_csv_file(filename)
print("\nMenu:")
print("4. Exit")
if choice == '1':
add_record_to_csv(filename)
display_csv_content(data)
search_csv_by_name(data, name)
print("Exiting program.")
break
else:
if __name__ == "__main__":
menu_csv()
Output:
3.) MYSQL:-
\
iv) Display activity name, Participants Num from the above table.
vi) Display all records where prize money is less than 10000.
#Consider the following tables RESORT:
Table:departments
Table:employees
i.) INSERT INTO departments (department_name) VALUES ('HR'), ('Finance'), ('IT'), ('Marketing');
ii.) Insert Data into the employees Table:
Table: courses
Table: students
Python code:
import mysql.connector
def connect_to_db():
try:
connection = mysql.connector.connect(
host='localhost',
user='root',
password='aksh9906'
if connection.is_connected():
return connection
except Error as e:
return None
def create_database_and_table(connection):
try:
cursor = connection.cursor()
cursor.execute("USE my_database")
cursor.execute("""
CREATE TABLE IF NOT EXISTS my_table (
""")
except Error as e:
finally:
cursor.close()
def create_record(connection):
try:
cursor = connection.cursor()
cursor.execute("INSERT INTO my_table (name, age) VALUES (%s, %s)", (name, age))
connection.commit()
except Error as e:
finally:
cursor.close()
def read_records(connection):
"""Read all records from the table."""
try:
cursor = connection.cursor()
rows = cursor.fetchall()
print("\nAll Records:")
except Error as e:
finally:
cursor.close()
def read_selected_record(connection):
try:
cursor = connection.cursor()
row = cursor.fetchone()
if row:
else:
except Error as e:
finally:
cursor.close()
def update_record(connection):
try:
cursor = connection.cursor()
connection.commit()
except Error as e:
finally:
cursor.close()
def delete_record(connection):
try:
cursor = connection.cursor()
connection.commit()
except Error as e:
cursor.close()
def main():
connection = connect_to_db()
if connection is None:
return
create_database_and_table(connection)
while True:
print("\nMenu:")
print("6. Exit")
if choice == '1':
create_record(connection)
read_records(connection)
read_selected_record(connection)
elif choice == '4':
update_record(connection)
delete_record(connection)
print("Exiting...")
break
else:
if connection.is_connected():
connection.close()
print("Connection closed.")
if __name__ == "__main__":
main()
Output: