Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
2 views

Comp practical file

The document contains a series of programming exercises and solutions related to Python, including string manipulation, dictionary creation, arithmetic operations, prime number finding, file handling, and database interactions with MySQL. Each exercise is presented with a problem statement followed by a Python code solution. The exercises cover a range of topics suitable for a programming curriculum, focusing on practical applications of Python functions and database operations.

Uploaded by

Ayaan Katyal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Comp practical file

The document contains a series of programming exercises and solutions related to Python, including string manipulation, dictionary creation, arithmetic operations, prime number finding, file handling, and database interactions with MySQL. Each exercise is presented with a problem statement followed by a Python code solution. The exercises cover a range of topics suitable for a programming curriculum, focusing on practical applications of Python functions and database operations.

Uploaded by

Ayaan Katyal
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 21

Practical file Questions

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)

print("Choose an option from the following- 1---Reverse the string, 2---


Replace ‘s’ or ‘S’ with “#”, 3---Find the repeating elements, 4---Encode
the string")
str1 = input("Enter a String Value: ")
ch = int(input("Enter your choice: "))
if ch == 1:
rev(str1)
elif ch == 2:
rep(str1)
elif ch == 3:
findrep(str1)
elif ch == 4:
encode(str1)
else:
print("Invalid Choice")

2. Write a program to create a dictionary containing names of books


as keys and authors as values.
Ans.
D1 ={}
n =int(input("Enter the No. of Books to be Added: "))
print()
for i in range(n):
k = input("Enter the Book Name: ")
v = input("Enter the Author Name: ")
print()
D1[k] = v
print(D1)

3. Write a program that receives two numbers in a function and


returns the results of all arithmetic operations on these numbers.
Ans.
def ar(a,b):
return [a+b,a-b,a*b,a/b]
x=float(input('enter the first number: '))
y=float(input('enter the second number: '))
print('the sum of numbers is: ', ar(x,y)[0])
print('the difference between the two numbers is: ',ar(x,y)[1])
print('the product of two numbers is: ', ar(x,y)[2])
print('the divison of the two numbers: ',ar(x,y)[3])
4. Write a function in Python to find and display the prime numbers
between 2 to N. Pass N as an argument to the function.
Ans.
def findprim(a):
p =[]
for j in range(2, a + 1):
l = []
for i in range(1, j + 1):
if j % i == 0:
l.append(i)
if len(l) == 2:
p.append(j)
for k in range(len(p)- 1):
print(p[k], end=",")
print(p[-1])

N=int(input("Enter a No.: "))


print("Prime No.s from 2 to", N, ":", end=" ")
findprim(N)

5. Write a function fiveEnding (SCORES) to add all those values in


the list of SCORES, which are ending with five (5) and display the
sum.
Ans.
def fiveEnding(SCORES):
s=0
for i in SCORES:
if i % 10 == 5:
s += i
print("The sum of all the numbers ending with 5 is:", s)
SCORES=[]
n =int(input("Enter no. of values: "))
print()
for j in range(n):
a =int(input("Enter a value: "))
SCORES.append(a)
print()
fiveEnding(SCORES)

6. Assuming that a text file named practical.txt contains some text


written into it, write a function that reads the file practical.txt and
creates a new file named response.txt, to contain only those
words from the file practical.txt which have 5 characters. For
example, if the file practical.txt contains, ‘Carry umbrella and
overcoat when it rains’, then the file response.txt shall contain
‘Carry rains’.
Ans.
def words_of_length(s):
t=f.read().replace("\n"," ")
l=t.split(" ")
n=open("response.txt","w")
for i in l:
if len(i)==s:
n.write(i)
n.write(' ')
f=open("practical.txt",'r')
words_of_length(5)

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:

 Storing the contact numbers of people


 Searching for the Contact Number using the person’s name
 Displaying the data in the directory
 Updating the persons contact number using the person’s
name
Ans.
def add_cont(name,number):
f=open("Phonebook.txt","a")
f.write(name+"-- "+number+"\n")
f.close()

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

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")

choice = input("Enter your choice: ")

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)

12. Write a program to insert multiple records onto mysql table


Employee using Python and also display all the records present
in the table.
Ans.
import mysql.connector
# Establish a connection to the MySQL database
db = mysql.connector.connect(
host="localhost",
user="root",
password="adiT123$",
database="employee"
)

# Create a cursor object to execute SQL queries


cursor = db.cursor()

# Insert multiple records into the Employee table


records_to_insert = [
("John", "Doe", 25, "Software Engineer"),
("Jane", "Doe", 30, "Data Scientist"),
("Bob", "Smith", 35, "DevOps Engineer"),
("Alice", "Johnson", 28, "QA Engineer")
]

query = "INSERT INTO Employee (first_name, last_name, age, job_title)


VALUES (%s, %s, %s, %s)"
cursor.executemany(query, records_to_insert)

# Commit the changes


db.commit()

# Display all records present in the Employee table


query = "SELECT * FROM Employee"
cursor.execute(query)

# Fetch all the rows


rows = cursor.fetchall()

print("All records in the Employee table:")


for row in rows:
print(f"ID: {row[0]}, First Name: {row[1]}, Last Name: {row[2]},
Age: {row[3]}, Job Title: {row[4]}")

# Close the cursor and connection


cursor.close()
db.close()

13. Create a menu driven application with options add modify


delete and display data from MySQL table Customer with fields
accno, name, balance, mobno and emailID.
Ans.
import mysql.connector

# Establish a connection to the MySQL database


db = mysql.connector.connect(
host="localhost",
user="root",
password="adiT123$",
database="employee"
)

# Create a cursor object to execute SQL queries


cursor = db.cursor()

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")

choice = input("Enter your choice: ")

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()

You might also like