Comp practical file
Comp practical file
Term 1
Ayaan katyal
XII -C
1. Write a menu driven program to accept a string from the user and
perform the following on it using functions:
• Reverse
• replace ‘s’ or ‘S’ with “#”
• Find the repeating characters in the string.
• Encode the string by adding 2 to each ASCII value.
Ans.
def rev(a):
print(a[-1::-1])
def rep(a):
print(a.replace('s', '#').replace('S', '#'))
def findrep(a):
l = []
for i in a:
if a.count(i) > 1 and i not in l:
l.append(i)
print("The repeating elements are:", end=" ")
if len(l) > 0:
for j in range(len(l)- 1):
print(l[j], end=",")
print(l[-1])
else:
print("None")
def encode(a):
s = ''
for i in a:
s += (chr(ord(i) + 2))
print("Encoded string is:", s)
7. Write a menu driven program to add, and display data from a text
file. The text file contains bank details (Account number, name
and balance).
Ans.
while True:
print(' Menu: 1> Add Data, 2> View Data 3> Exit ')
user_input = int(input("Enter your choice: "))
if user_input == 1:
f=open("Bank Details.txt","a")
while True:
acc_no = int(input("Enter your account number: "))
name = input("Enter your account holder name: ")
balance = int(input("Enter your account balance: "))
f.write(str(acc_no)+" "+name+" "+str(balance)+"\n")
cont = input("Do you want to add more data (y/n): ")
if cont == "n":
break
if user_input == 2:
f=open("Bank Details.txt","r")
while True:
rec=f.readline().split()
print()
print("Account Number:",rec[0])
print("Account Holder Name:",rec[1])
print("Account Balance:",rec[2])
print()
cont = input("Do you want to display more data (y/n): ")
if cont == "n":
break
if user_input == 3:
print("Thank you for using our banking system.")
break
8. Write a menu-driven program, to create a Phonebook Directory
(Phonebook.txt) using different functions. The functions have to
be created for the following features of the Phonebook Directory:
def search_cont(NM):
re=open("Phonebook.txt","r")
for i in re.readlines():
lst=i.split('-- ')
if lst[0]==NM:
for j in lst:
print(j,end=" ")
re.close()
def display_cont():
d=open("Phonebook.txt","r")
for i in d.readlines():
print(i)
d.close()
def update_cont(NM,NN):
PF=open("Phonebook.txt","r")
rec=PF.readlines()
lst=[]
lst1=[]
k=0
for i in rec:
lst.append(i.split(' -- '))
for i in range(0,len(lst),2):
lst1.append(lst[i])
for i in lst1:
if i==NM:
break
k+=1
rec[k]=(NM+"-- "+str(NN)+"\n")
NF=open("Phonebook.txt","w")
NF.writelines(rec)
PF.close()
NF.close()
while True:
print( 'Phonebook Directory Menu: 1> Add a new contact, 2> Search
for a contact, 3> Display all contacts, 4> Update a contact, 5> Exit')
choice=int(input("Enter your choice: "))
if choice==1:
name=input("Enter the Full Name: ")
number=input("Enter the Number: ")
add_cont(name,number)
elif choice==2:
name=input("Enter the Full Name: ")
search_cont(name)
elif choice==3:
display_cont()
elif choice==4:
name=input("Enter the Full Name: ")
number=input("Enter the Number: ")
update_cont(name,number)
elif choice==5:
print("Program Ended.")
break
def modify_customer():
accno = input("Enter account number to modify: ")
query = "SELECT * FROM Customer WHERE accno = %s"
cursor.execute(query, (accno,))
row = cursor.fetchone()
if row:
print("Current details:")
print(f"Name: {row[1]}, Balance: {row[2]}, Mobile Number:
{row[3]}, Email ID: {row[4]}")
name = input("Enter new name (press enter to keep current): ")
balance = input("Enter new balance (press enter to keep current):
")
mobno = input("Enter new mobile number (press enter to keep
current): ")
emailID = input("Enter new email ID (press enter to keep current):
")
if name:
query = "UPDATE Customer SET name = %s WHERE accno = %s"
cursor.execute(query, (name, accno))
if balance:
query = "UPDATE Customer SET balance = %s WHERE accno =
%s"
cursor.execute(query, (float(balance), accno))
if mobno:
query = "UPDATE Customer SET mobno = %s WHERE accno =
%s"
cursor.execute(query, (mobno, accno))
if emailID:
query = "UPDATE Customer SET emailID = %s WHERE accno =
%s"
cursor.execute(query, (emailID, accno))
db.commit()
print("Customer details modified successfully!")
else:
print("Account number not found!")
def delete_customer():
accno = input("Enter account number to delete: ")
query = "DELETE FROM Customer WHERE accno = %s"
cursor.execute(query, (accno,))
db.commit()
print("Customer deleted successfully!")
def display_customers():
query = "SELECT * FROM Customer"
cursor.execute(query)
rows = cursor.fetchall()
print("\nCustomer Details:")
print("-------------------")
for row in rows:
print(f"Account Number: {row[0]}")
print(f"Name: {row[1]}")
print(f"Balance: {row[2]}")
print(f"Mobile Number: {row[3]}")
print(f"Email ID: {row[4]}")
print("-------------------")
while True:
print("\nMenu:")
print("1. Add Customer")
print("2. Modify Customer")
print("3. Delete Customer")
print("4. Display Customers")
print("5. Exit")
if choice == "1":
add_customer()
elif choice == "2":
modify_customer()
elif choice == "3":
delete_customer()
elif choice == "4":
display_customers()
elif choice == "5":
break
else:
print("Invalid choice. Please try again.")
cursor.close()
db.close()
10 write a program to show all the tables that exist in MySQL using
Python Interface.
Ans.
import mysql.connector
conn = mysql.connector.connect(host = 'localhost', user = 'root',
password = 'adiT123$', database = 'flights')
c = conn.cursor()
c.execute("SHOW TABLES")
for i in c:
print(i)
11. Write a program to check for all the databases,
present in MySQL using Python.
Ans.
import mysql.connector
conn = mysql.connector.connect(host = 'localhost', user = 'root',
password = 'adiT123$', database = 'flights')
c = conn.cursor()
c.execute("SHOW DATABASES")
for i in c:
print(i)
def add_customer():
accno = input("Enter account number: ")
name = input("Enter customer name: ")
balance = float(input("Enter initial balance: "))
mobno = input("Enter mobile number: ")
emailID = input("Enter email ID: ")
query = "INSERT INTO Customer (accno, name, balance, mobno,
emailID) VALUES (%s, %s, %s, %s, %s)"
cursor.execute(query, (accno, name, balance, mobno, emailID))
db.commit()
print("Customer added successfully!")
def modify_customer():
accno = input("Enter account number to modify: ")
query = "SELECT * FROM Customer WHERE accno = %s"
cursor.execute(query, (accno,))
row = cursor.fetchone()
if row:
print("Current details:")
print(f"Name: {row[1]}, Balance: {row[2]}, Mobile Number:
{row[3]}, Email ID: {row[4]}")
name = input("Enter new name (press enter to keep current): ")
balance = input("Enter new balance (press enter to keep current):
")
mobno = input("Enter new mobile number (press enter to keep
current): ")
emailID = input("Enter new email ID (press enter to keep current):
")
if name:
query = "UPDATE Customer SET name = %s WHERE accno = %s"
cursor.execute(query, (name, accno))
if balance:
query = "UPDATE Customer SET balance = %s WHERE accno =
%s"
cursor.execute(query, (float(balance), accno))
if mobno:
query = "UPDATE Customer SET mobno = %s WHERE accno =
%s"
cursor.execute(query, (mobno, accno))
if emailID:
query = "UPDATE Customer SET emailID = %s WHERE accno =
%s"
cursor.execute(query, (emailID, accno))
db.commit()
print("Customer details modified successfully!")
else:
print("Account number not found!")
def delete_customer():
accno = input("Enter account number to delete: ")
query = "DELETE FROM Customer WHERE accno = %s"
cursor.execute(query, (accno,))
db.commit()
print("Customer deleted successfully!")
def display_customers():
query = "SELECT * FROM Customer"
cursor.execute(query)
rows = cursor.fetchall()
print("\nCustomer Details:")
print("-------------------")
for row in rows:
print(f"Account Number: {row[0]}")
print(f"Name: {row[1]}")
print(f"Balance: {row[2]}")
print(f"Mobile Number: {row[3]}")
print(f"Email ID: {row[4]}")
print("-------------------")
while True:
print("\nMenu:")
print("1. Add Customer")
print("2. Modify Customer")
print("3. Delete Customer")
print("4. Display Customers")
print("5. Exit")
if choice == "1":
add_customer()
elif choice == "2":
modify_customer()
elif choice == "3":
delete_customer()
elif choice == "4":
display_customers()
elif choice == "5":
break
else:
print("Invalid choice. Please try again.")
# Close the cursor and connection
cursor.close()
db.close()