1.
Functions
# 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
for num in args:
total_product *= num
return total_sum, total_product
numbers = range(1, 11)
result_sum, result_product = calculate_sum_and_product(*numbers)
print("The sum of the first 10 numbers is:", result_sum)
print("The product of the first 10 numbers is:", result_product)
Output:
#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:
#Write a python program to reverse a string
Python code:-
def string_reverse(str1):
rstr1 = ''
index = len(str1)
while index > 0:
rstr1 += str1[index - 1]
index -= 1
return rstr1
# Test the function
print(string_reverse('python123'))
Output:
#write recursive code to compute and print sum of squares of numbers .value of n is passed as
parameter.
Python code:-
def sqsum(n):
if n == 1:
return 1
else:
return n * n + sqsum(n - 1)
# Main program
n = int(input("Enter value of n: "))
print("The sum of squares up to", n, "is:", sqsum(n))
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
the key
Python code:-
def findname(name):
if name in phonebook:
del phonebook[name]
print(f"Entry for {name} has been deleted.")
else:
print("Name not found")
print("Phonebook Information")
print("Name", '\t', "Phone Number")
for i in phonebook.keys():
print(i, '\t', phonebook[i])
# Example phonebook dictionary
phonebook = {
"Aksh": "987-372-5599",
"Bhavya": "987-654-3210",
"Chirag": "555-555-5555"
# Testing the function
findname("Aksh")
Output:
# write a Python program that prints the even numbers from a given list.
Python code:-
def is_even_num(l):
enum = []
for n in l:
if n % 2 == 0:
enum.append(n)
return enum
print (is_even_num([1, 2, 3, 4, 5, 6, 7, 8, 9]))
Output:
2. Data File handling
TEXT FILE Programs:
# Write a Python program that reads a file named letter.txt, counts all the words, and displays
the words that have exactly 5 characters, follow the steps below:
Python code
def count_words_and_display_five_char_words(file_name):
try:
with open(file_name, 'r') as file:
content = file.read()
# Split the content into words
words = content.split()
# Initialize the counters
total_words = len(words)
five_char_words = [word for word in words if len(word) == 5]
# Display the results
print(f"Total number of words: {total_words}")
print("Words with exactly 5 characters:")
for word in five_char_words:
print(word)
except FileNotFoundError:
print(f"Error: The file '{file_name}' was not found.")
# Main program execution
file_name = 'letter.txt'
count_words_and_display_five_char_words(file_name)
output:
#WAP that reads a txt file “story.txt" and do the following 1. ) count the total characters
2.) Count total lines
3.) Count total words
4.) Count total words in each line
5.) Count the no of uppercase lowercase and digits in file.
6.) Count the occurrence of "me" and "my" words in the file.
7.) Count the no. of lines starts with "the".
8.) Count the word that ends with "Y"
9.) Count the words that starts with vowels
10. ) display the sum the digits present in the file
11.) Display total vowel and consonants in the file .
12.) copy the content of story.txt to st"st.txt"
13.) Search the given word in the text file and display its occurrences and position
14.) Replace "I" with "s" where ever it appears.
Python Code:
def text_file_analysis(file_path):
try:
with open(file_path, 'r') as file:
content = file.read()
file.seek(0)
lines = file.readlines()
# 1. Count total characters
total_characters = len(content)
# 2. Count total lines
total_lines = len(lines)
# 3. Count total words
words = content.split()
total_words = len(words)
# 4. Count total words in each line
words_in_each_line = [len(line.split()) for line in lines]
# 5. Count uppercase, lowercase, and digits
uppercase_count = sum(1 for c in content if c.isupper())
lowercase_count = sum(1 for c in content if c.islower())
digit_count = sum(1 for c in content if c.isdigit())
# 6. Count occurrences of "me" and "my"
me_count = content.lower().split().count('me')
my_count = content.lower().split().count('my')
# 7. Count lines starting with "the"
lines_starting_with_the = sum(1 for line in lines if line.lower().startswith('the'))
# 8. Count words ending with "Y"
words_ending_with_y = sum(1 for word in words if word.lower().endswith('y'))
# 9. Count words starting with vowels
vowels = ('a', 'e', 'i', 'o', 'u')
words_starting_with_vowel = sum(1 for word in words if word.lower().startswith(vowels))
# 10. Sum of digits present in the file
digits_in_content = [int(c) for c in content if c.isdigit()]
sum_of_digits = sum(digits_in_content)
# 11. Count total vowels and consonants
vowel_count = sum(1 for c in content.lower() if c in vowels)
consonant_count = sum(1 for c in content.lower() if c.isalpha() and c not in vowels)
# 12. Copy content to "st.txt"
with open('st.txt', 'w') as st_file:
st_file.write(content)
# 13. Search for a word and display occurrences and positions
search_word = input("Enter the word to search: ").strip()
word_occurrences = 0
word_positions = []
for idx, word in enumerate(words):
if word.strip('.,!?;"\'').lower() == search_word.lower():
word_occurrences += 1
word_positions.append(idx + 1) # Position starts from 1
# 14. Replace "I" with "s" wherever it appears
replaced_content = content.replace('I', 's').replace('i', 's')
with open('story_replaced.txt', 'w') as replaced_file:
replaced_file.write(replaced_content)
# Displaying all results
print(f"Total characters: {total_characters}")
print(f"Total lines: {total_lines}")
print(f"Total words: {total_words}")
print(f"Words in each line: {words_in_each_line}")
print(f"Uppercase letters: {uppercase_count}")
print(f"Lowercase letters: {lowercase_count}")
print(f"Digits: {digit_count}")
print(f"Occurrences of 'me': {me_count}")
print(f"Occurrences of 'my': {my_count}")
print(f"Lines starting with 'the': {lines_starting_with_the}")
print(f"Words ending with 'Y': {words_ending_with_y}")
print(f"Words starting with a vowel: {words_starting_with_vowel}")
print(f"Sum of digits in file: {sum_of_digits}")
print(f"Total vowels: {vowel_count}")
print(f"Total consonants: {consonant_count}")
print(f"Occurrences of '{search_word}': {word_occurrences}")
print(f"Positions of '{search_word}': {word_positions}")
print("Content copied to 'st.txt'")
print("Content with 'I' replaced by 's' saved to 'story_replaced.txt'")
except FileNotFoundError:
print(f"Error: The file '{file_path}' was not found.")
except Exception as e:
print(f"An error occurred: {e}")
# Main execution
if __name__ == "__main__":
text_file_path = 'story.txt'
text_file_analysis(text_file_path)
Output:
Binary File Programs:
#Menu-Driven Program for List Operations on a Binary File
Python code:-
import pickle
def write_list_to_file(filename, data_list):
"""Writes a list to a binary file."""
with open(filename, 'wb') as file:
pickle.dump(data_list, file)
print("Data written to file successfully.")
def read_list_from_file(filename):
"""Reads a list from a binary file."""
try:
with open(filename, 'rb') as file:
data_list = pickle.load(file)
return data_list
except FileNotFoundError:
print("File not found.")
return []
except EOFError:
print("File is empty.")
return []
def display_list(data_list):
"""Displays the items in the list."""
if not data_list:
print("The list is empty.")
else:
print("\nList Contents:")
for i, item in enumerate(data_list, start=1):
print(f"{i}. {item}")
def search_item_in_list(data_list, item):
"""Searches for an item in the list and displays its index if found."""
if item in data_list:
index = data_list.index(item)
print(f"Item '{item}' found at position {index + 1}.")
else:
print(f"Item '{item}' not found in the list.")
def update_item_in_list(data_list, index, new_item):
"""Updates an item in the list at a given index."""
if 0 <= index < len(data_list):
old_item = data_list[index]
data_list[index] = new_item
print(f"Item '{old_item}' updated to '{new_item}'.")
else:
print("Invalid index.")
def menu_list():
filename = 'list_data.bin'
data_list = read_list_from_file(filename)
while True:
print("\nMenu:")
print("1. Add item to list")
print("2. Display list")
print("3. Delete item from list")
print("4. Search for an item")
print("5. Update an item")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
item = input("Enter item to add: ")
data_list.append(item)
write_list_to_file(filename, data_list)
print(f"Item '{item}' added successfully.")
elif choice == '2':
display_list(data_list)
elif choice == '3':
display_list(data_list)
index = int(input("Enter the index of the item to delete: ")) - 1
if 0 <= index < len(data_list):
del_item = data_list.pop(index)
write_list_to_file(filename, data_list)
print(f"Item '{del_item}' deleted successfully.")
else:
print("Invalid index.")
elif choice == '4':
item = input("Enter item to search: ")
search_item_in_list(data_list, item)
elif choice == '5':
display_list(data_list)
index = int(input("Enter the index of the item to update: ")) - 1
if 0 <= index < len(data_list):
new_item = input("Enter the new item: ")
update_item_in_list(data_list, index, new_item)
write_list_to_file(filename, data_list)
else:
print("Invalid index.")
elif choice == '6':
print("Exiting program.")
break
else:
print("Invalid choice, please try again.")
# Main execution for list menu
if __name__ == "__main__":
menu_list()
Output:
#File Content for Dictionary Operations: dict_operations.py
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"
with open(filename, 'wb') as file:
pickle.dump(sample_dict, file)
print(f"Dictionary binary file '{filename}' created and initialized with sample data.")
def write_dict_to_file(filename, data_dict):
"""Writes a dictionary to a binary file."""
with open(filename, 'wb') as file:
pickle.dump(data_dict, file)
print("Data written to file successfully.")
def read_dict_from_file(filename):
"""Reads a dictionary from a binary file."""
try:
with open(filename, 'rb') as file:
data_dict = pickle.load(file)
return data_dict
except FileNotFoundError:
print("File not found. Returning an empty dictionary.")
return {}
except EOFError:
print("File is empty. Returning an empty dictionary.")
return {}
def display_dict(data_dict):
"""Displays all key-value pairs in the dictionary."""
if not data_dict:
print("The dictionary is empty.")
else:
print("\nDictionary Contents:")
for key, value in data_dict.items():
print(f"{key}: {value}")
def search_key_in_dict(data_dict, key):
"""Searches for a key in the dictionary and displays its value if found."""
if key in data_dict:
print(f"Key '{key}' found with value: {data_dict[key]}")
else:
print(f"Key '{key}' not found in the dictionary.")
def menu_dict():
filename = 'dict_data.bin'
initialize_dict_file(filename)
data_dict = read_dict_from_file(filename)
while True:
print("\nMenu:")
print("1. Add or update key-value pair")
print("2. Display dictionary")
print("3. Delete key from dictionary")
print("4. Search for a key")
print("5. Exit")
choice = input("Enter your choice: ")
if choice == '1':
key = input("Enter key: ")
value = input("Enter value: ")
data_dict[key] = value
write_dict_to_file(filename, data_dict)
print(f"Key '{key}' added/updated successfully.")
elif choice == '2':
display_dict(data_dict)
elif choice == '3':
key = input("Enter the key to delete: ")
if key in data_dict:
del data_dict[key]
write_dict_to_file(filename, data_dict)
print(f"Key '{key}' deleted successfully.")
else:
print("Key not found.")
elif choice == '4':
key = input("Enter the key to search: ")
search_key_in_dict(data_dict, key)
elif choice == '5':
print("Exiting program.")
break
else:
print("Invalid choice, please try again.")
# Main execution for dictionary menu
if __name__ == "__main__":
menu_dict()
# Main execution for dictionary menu
menu_dict()
Output:
C.S.V File program
# C. S.V file program Menu Driven complete program
Python code:-
import csv
import os
def initialize_csv_file(filename):
"""Initialize the CSV file with sample data if it doesn't exist."""
if not os.path.isfile(filename):
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
# Write sample header and data
writer.writerow(["ID", "Name", "Age", "City"])
writer.writerow([1, "Alice", 30, "Wonderland"])
writer.writerow([2, "Bob", 25, "Builderland"])
print(f"CSV file '{filename}' created and initialized with sample data.")
def display_csv(filename):
"""Display all records in the CSV file."""
if not os.path.isfile(filename):
print("File not found.")
return
with open(filename, 'r') as file:
reader = csv.reader(file)
for row in reader:
print(", ".join(row))
def add_record(filename):
"""Add a new record to the CSV file."""
id = input("Enter ID: ")
name = input("Enter Name: ")
age = input("Enter Age: ")
city = input("Enter City: ")
with open(filename, 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow([id, name, age, city])
print("Record added successfully.")
def search_record(filename):
"""Search for a record in the CSV file by ID."""
id_to_search = input("Enter ID of the record to search: ")
found = False
with open(filename, 'r') as file:
reader = csv.reader(file)
for row in reader:
if row[0] == id_to_search:
print("Record found:")
print(", ".join(row))
found = True
break
if not found:
print("Record not found.")
def menu_csv():
filename = 'records.csv'
initialize_csv_file(filename)
while True:
print("\nMenu:")
print("1. Display all records")
print("2. Add a record")
print("3. Search for a record")
print("4. Exit")
choice = input("Enter your choice: ")
if choice == '1':
display_csv(filename)
elif choice == '2':
add_record(filename)
elif choice == '3':
search_record(filename)
elif choice == '4':
print("Exiting program.")
break
else:
print("Invalid choice, please try again.")
# Main execution for CSV menu
if __name__ == "__main__":
menu_csv()
Output:
3.) MYSQL:-
# Do SQL Queries Consider the following table:
i) Create the above table in the database DB1.
ii) Add all the records in the above table.
iii) Display all records.
iv) Display activity name, Participants Num from the above table.
v) Display those activities where participant’s num is above 10.
vi) Display all records where prize money is less than 10000.
#Consider the following tables RESORT:
i) Create the above table in the database DB1.
ii) Add all the records in the above table.
iii) Display all records.
iv) Display Resorts code that exists in "Goa".
v) Display records that rent falls in 10000-13000.
# write sql quires for (i) (v) which are based on the table
Creating database and table:-
(i) To display details of all transactions of TYPE Withdraw from TRANSACT table:
(ii) To display ANO and AMOUNT of all Deposit and Withdrawals done in the month of ‘May’ 2017
from table TRANSACT:
(iii) To display first date of transaction (DOT) from table TRANSACT for Account having ANO as 102:
(iv) To display ANO, ANAME, AMOUNT, and DOT of those persons from ACCOUNT and TRANSACT
tables who have done transactions less than or equal to 3000:
(v) SELECT ANO, ANAME FROM ACCOUNT WHERE ADDRESS NOT IN ('CHENNAI', 'BANGALORE');
#Write queries for (i) to (v) and find ouputs for SQL queries
Create database and table vehicle travel
(i) Display CNO, CNAME, and TRAVELDATE from the TRAVEL table in descending order of CNO:
(ii) Display the CNAME of all customers from the TRAVEL table who are traveling by vehicle with code
V01 or V02:
(iii) Display the CNO and CNAME of those customers from the TRAVEL table who traveled between
2015-12-31 and 2015-05-01:
(iv) Display all the details from the TRAVEL table for the customers who have traveled a distance of
more than 120 KM in ascending order of NOP:
(v) SELECT COUNT (*), VCODE FROM TRAVEL GROUP BY VCODE HAVING COUNT(*) > 1;
Alter Table clauses on the above table
a) Add a column to the above table.
b) Change the Name of any Column.
c) Modify the data type of any column.
d) Remove any Column.
e) Add a primary key to the above table.
#Python and Sql Connectivity menu driven program
Python code:
import mysql.connector
from mysql.connector import Error
def connect_to_db():
try:
connection = mysql.connector.connect(
host='localhost',
user='root',
password='aksh9906'
if connection.is_connected():
print("Connected to MySQL server.")
return connection
except Error as e:
print(f"Error: {e}")
return None
def create_database_and_table(connection):
try:
cursor = connection.cursor()
# Create database if it does not exist
cursor.execute("CREATE DATABASE IF NOT EXISTS my_database")
# Select the database
cursor.execute("USE my_database")
# Create table if it does not exist
cursor.execute("""
CREATE TABLE IF NOT EXISTS my_table (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
age INT NOT NULL
""")
print("Database and table setup complete.")
except Error as e:
print(f"Error: {e}")
def create_record(cursor):
name = input("Enter name: ")
age = int(input("Enter age: "))
try:
cursor.execute("INSERT INTO my_table (name, age) VALUES (%s, %s)", (name, age))
print("Record inserted successfully.")
except Error as e:
print(f"Error: {e}")
def read_records(cursor):
try:
cursor.execute("SELECT * FROM my_table")
rows = cursor.fetchall()
print("\nAll Records:")
for row in rows:
print(f"ID: {row[0]}, Name: {row[1]}, Age: {row[2]}")
except Error as e:
print(f"Error: {e}")
def read_selected_record(cursor):
id = int(input("Enter the ID of the record to display: "))
try:
cursor.execute("SELECT * FROM my_table WHERE id = %s", (id,))
row = cursor.fetchone()
if row:
print(f"ID: {row[0]}, Name: {row[1]}, Age: {row[2]}")
else:
print("Record not found.")
except Error as e:
print(f"Error: {e}")
def update_record(cursor):
id = int(input("Enter the ID of the record to update: "))
new_name = input("Enter the new name: ")
new_age = int(input("Enter the new age: "))
try:
cursor.execute("UPDATE my_table SET name = %s, age = %s WHERE id = %s", (new_name,
new_age, id))
print("Record updated successfully.")
except Error as e:
print(f"Error: {e}")
def delete_record(cursor):
id = int(input("Enter the ID of the record to delete: "))
try:
cursor.execute("DELETE FROM my_table WHERE id = %s", (id,))
print("Record deleted successfully.")
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()
while True:
print("\nMenu:")
print("1. Create Record")
print("2. Read All Records")
print("3. Read Selected Record")
print("4. Update Record")
print("5. Delete Record")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
create_record(cursor)
connection.commit()
elif choice == '2':
read_records(cursor)
elif choice == '3':
read_selected_record(cursor)
elif choice == '4':
update_record(cursor)
connection.commit()
elif choice == '5':
delete_record(cursor)
connection.commit()
elif choice == '6':
print("Exiting...")
break
else:
print("Invalid choice. Please try again.")
cursor.close()
connection.close()
if __name__ == "__main__":
main()
Output: