Uploaded by RK Project Zone

answer

advertisement
Assignment Work
Q1. Write a menu driven program to do the following tasks with the help of user-defined
functions
1) Find factorial of a number
2) Check if the number is prime or not
3) Fibonacci series up to n terms
Answer:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)
def is_prime(n):
if n <= 1:
return "Not Prime"
elif n == 2:
return "Prime"
elif n % 2 == 0:
return "Not Prime"
else:
for i in range(3, int(n ** 0.5) + 1, 2):
if n % i == 0:
return "Not Prime"
return "Prime"
def fibonacci(n):
fib_series = [0, 1]
while len(fib_series) < n:
next_num = fib_series[-1] + fib_series[-2]
fib_series.append(next_num)
return fib_series
while True:
print("Choose an option:")
print("1. Find factorial of a number")
print("2. Check if a number is prime")
print("3. Generate Fibonacci series")
print("4. Quit")
choice = input("Enter your choice (1/2/3/4): ")
if choice == '1':
num = int(input("Enter a number: "))
if num < 0:
print("Factorial is not defined for negative numbers.")
else:
result = factorial(num)
print("The factorial of"+ str(num)+ " is "+(result))
elif choice == '2':
num = int(input("Enter a number: "))
result = is_prime(num)
print(result)
elif choice == '3':
n = int(input("Enter the number of Fibonacci terms to generate: "))
if n <= 0:
print("Please enter a positive integer.")
else:
result = fibonacci(n)
print("Fibonacci series up to", n, "terms:")
print(result)
elif choice == '4':
print("Goodbye!")
break
else:
print("Invalid choice. Please select a valid option (1/2/3/4).")
output
Q2. Write a menu driven program to do the following tasks with the help of user-defined
functions
1) Calculate Simple Interest with r and t as default parameters
2)Calculate X**N with N as default parameter
Ans:
def calculate_simple_interest():
principal = float(input("Enter the principal amount: "))
rate = float(input("Enter the rate of interest (in decimal form, e.g., 0.05 for 5%): "))
time = int(input("Enter the time period in years: "))
simple_interest = principal * rate * time
print("The Simple Interest is:”+ str(simple_interest))
def calculate_power():
base = float(input("Enter the base number (X): "))
exponent = int(input("Enter the exponent (N): "))
result = base ** exponent
print(str(base) + " raised to the power of " + str(exponent) + " is: " + str(result))
while True:
print("Choose an option:")
print("1. Calculate Simple Interest")
print("2. Calculate X raised to the power of N")
print("3. Quit")
choice = input("Enter your choice (1/2/3): ")
if choice == '1':
calculate_simple_interest()
elif choice == '2':
calculate_power()
elif choice == '3':
print("Goodbye!")
break
else:
print("Invalid choice. Please select a valid option (1/2/3).")
Output
Q3. Write a menu driven program to do the following tasks with the help of user-defined
functions
1) To find length of a string
2) Check for palindrome
3) Change to uppercase
Reverse the string
Ans:
def find_string_length(input_string):
return len(input_string)
def is_palindrome(input_string):
return input_string == input_string[::-1]
def change_to_uppercase(input_string):
return input_string.upper()
def reverse_string(input_string):
return input_string[::-1]
def main_menu():
print("Choose an option:")
print("1. Find the length of a string")
print("2. Check if a string is a palindrome")
print("3. Change a string to uppercase")
print("4. Reverse a string")
print("5. Quit")
while True:
main_menu()
choice = input("Enter your choice (1/2/3/4/5): ")
if choice == '1':
input_string = input("Enter a string: ")
length = find_string_length(input_string)
print("The length of the string is: "+str(length))
elif choice == '2':
input_string = input("Enter a string: ")
if is_palindrome(input_string):
print("The string is a palindrome.")
else:
print("The string is not a palindrome.")
elif choice == '3':
input_string = input("Enter a string: ")
uppercase_string = change_to_uppercase(input_string)
print("The string in uppercase is: “ str(uppercase_string))
elif choice == '4':
input_string = input("Enter a string: ")
reversed_string = reverse_string(input_string)
print("The reversed string is: “ +str(reversed_string))
elif choice == '5':
print("Goodbye!")
break
else:
print("Invalid choice. Please select a valid option (1/2/3/4/5).")
Q4. Write a function in PYTHON to count and display the number of words starting with
alphabet ‘A’ or ‘a’ present in a text file “LINES.TXT”. Example: If the file “LINES.TXT” contains
the following lines, A boy is playing there. There is a playground.
An aeroplane is in the sky.
Are you getting it?
The function should display the output as 5
Ans:
def count_words_starting_with_a():
filename = "LINES.TXT"
with open(filename, 'r') as file:
content = file.read()
words = content.split()
count = 0
for word in words:
if word[0].lower() == 'a':
count += 1
return count
result = count_words_starting_with_a(filename)
if result == -1:
print("File not found:", filename)
elif result == -2:
print("An error occurred while processing the file.")
else:
print("Number of words starting with 'A' or 'a' in", filename, "is:", result)
Q5. Write a menu driven program to do the following tasks with the help of user-defined
functions
1)Write text to a file.
2)Display all data from file
3)Count and display the total alphabets and digits.
4)Count the total no. of times "the" word occurs.
5)Print the strings in reverse order.
Ans:
Code:
def write_text_to_file():
filename = "data.txt"
text = input("Enter the text to write to the file: ")
with open(filename, 'w') as file:
file.write(text)
print("Text written to “+ str(filename)+” successfully.")
def display_data_from_file():
filename = "data.txt"
with open(filename, 'r') as file:
data = file.read()
print("Data from the file:")
print(data)
def count_alphabets_and_digits():
filename = "data.txt"
with open(filename, 'r') as file:
data = file.read()
alphabets = sum(c.isalpha() for c in data)
digits = sum(c.isdigit() for c in data)
print("Total Alphabets: "+ str(alphabets))
print("Total Digits: "+ str(digits))
def count_occurrences_of_word( word):
filename = "data.txt"
with open(filename, 'r') as file:
data = file.read()
word_count = data.lower().count(word.lower())
print("The word ' "+ word +" occurs "+ str(word_count)+ " times in the file.")
def print_strings_in_reverse_order(filename):
filename = "data.txt"
with open(filename, 'r') as file:
lines = file.readlines()
print("Strings in reverse order:")
for line in reversed(lines):
print(line.strip())
def main_menu():
print("Choose an option:")
print("1. Write text to a file")
print("2. Display all data from the file")
print("3. Count and display total alphabets and digits")
print("4. Count the total number of times 'the' word occurs")
print("5. Print the strings in reverse order")
print("6. Quit")
while True:
main_menu()
choice = input("Enter your choice (1/2/3/4/5/6): ")
if choice == '1':
write_text_to_file()
elif choice == '2':
display_data_from_file()
elif choice == '3':
count_alphabets_and_digits()
elif choice == '4':
word = "the"
count_occurrences_of_word( word)
elif choice == '5':
print_strings_in_reverse_order()
elif choice == '6':
print("Goodbye!")
break
else:
print("Invalid choice. Please select a valid option (1/2/3/4/5/6).")
OUTPUT
Q6. Write a menu driven program to do the following tasks with the help of user-defined
functions
1)Replace 's' with 'S' in new file.
2)Count & display no. of words beginning with 'a' OR 'A'.
3)Count the no. of words beginning with 'a' or 'A' and ending with'e' or 'E'.
4)Replace 'DELHI' with 'NEWDELHI' in address.txt.
Ans:
def replace_s_with_S():
input_filename = "input.txt"
output_filename = "output.txt"
address_filename = "address.txt"
with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:
for line in infile:
updated_line = line.replace('s', 'S')
outfile.write(updated_line)
print("'s' replaced with 'S' in "+ str(output_file) +” successfully.")
def count_words_starting_with_a():
input_filename = "input.txt"
output_filename = "output.txt"
address_filename = "address.txt"
with open(input_file, 'r') as file:
data = file.read()
words = data.split()
count = sum(1 for word in words if word[0].lower() == 'a')
print("Number of words starting with 'a' or 'A': "+ str(count))
print("Input file not found:", input_file)
def count_words_starting_with_a_ending_with_e():
input_filename = "input.txt"
output_filename = "output.txt"
address_filename = "address.txt"
with open(input_file, 'r') as file:
data = file.read()
words = data.split()
count = sum(1 for word in words if word[0].lower() == 'a' and word[-1].lower() == 'e')
print("Number of words starting with 'a' or 'A' and ending with 'e' or 'E': "+ str(count))
def replace_delhi_with_newdelhi():
input_filename = "input.txt"
output_filename = "output.txt"
address_filename = "address.txt"
with open(input_file, 'r') as infile, open(output_file, 'w') as outfile:
for line in infile:
updated_line = line.replace('DELHI', 'NEWDELHI')
outfile.write(updated_line)
print("'DELHI' replaced with 'NEWDELHI' in "+ str(output_file)+ " successfully.")
def main_menu():
print("Choose an option:")
print("1. Replace 's' with 'S' in a new file")
print("2. Count and display the number of words starting with 'a' or 'A'")
print("3. Count the number of words starting with 'a' or 'A' and ending with 'e' or 'E'")
print("4. Replace 'DELHI' with 'NEWDELHI' in a file")
print("5. Quit")
while True:
main_menu()
choice = input("Enter your choice (1/2/3/4/5): ")
if choice == '1':
replace_s_with_S(input)
elif choice == '2':
count_words_starting_with_a()
elif choice == '3':
count_words_starting_with_a_ending_with_e()
elif choice == '4':
replace_delhi_with_newdelhi()
elif choice == '5':
print("Goodbye!")
break
else:
print("Invalid choice. Please select a valid option (1/2/3/4/5).")
Output
Q7. Given a binary file “STUDENT.DAT”, containing records of the following type: [S_Admno,
S_Name, Percentage] Where these three values are: S_Admno – Admission Number of
student (string) S_Name – Name of student (string) Percentage – Marks percentage of
student (float) Write a function in PYTHON that would read contents of the file
“STUDENT.DAT” and display the details of those students whose percentage is above 75
Ans:
import struct
def display_students_above_percentage():
filename = "STUDENT.DAT"
findmarks = 75.0
try:
with open(filename, 'rb') as file:
while True:
record = struct.unpack("20s20sf", file.read(struct.calcsize("20s20sf")))
if not record[0]:
break
S_Admno, S_Name, Percentage = record
if Percentage > threshold:
print("Admission Number: ", S_Admno)
print("Name: ",S_Name)
print("Percentage: ",Percentage)
print()
except Exception as e:
print("An error occurred: ", e)
# Usage: Display students with a percentage above 75 from STUDENT.DAT
display_students_above_percentage()
Output
Q8. Write a definition for function BUMPER () in PYTHON to read each object of a binary file
GIFTS.DAT, find and display details of those gifts, which have remarks as “ON DISCOUNT”.
Assume that the file GIFTS.DAT is created with the help of lists of following type:
(ID, Gift, Remarks, Price)
Ans:
import pickle
def BUMPER():
filename = "GIFTS.DAT"
try:
with open(filename, 'rb') as file:
c=0
while True:
try:
record = pickle.load(file)
if record[2] == 'ON DISCOUNT':
print("ID: ",record[0])
print("Gift: ",record[1])
print("Remarks: ",record[2])
print("Price: ",record[3])
print()
c += 1
except EOFError:
break
print("Total gifts on discount: ",c)
except Exception as e:
print("An error occurred: ",e)
BUMPER(filename)
Q9. Create a csv file using MS-Excel with the following data:
Name, Age, Qualification, Experience
Ananya,32, PG, 8
Then, write a menu driven program to perform the following operations on the file:
(i) Append record(s) to the file
(ii) Display all the data from the file
(iii)Display all the records with Age<30
(iv)Increase the Experience of all the records by 1
(v) Delete a record with given name and age (to be input from the user).
Ans:
import csv
def write_csv_header():
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(["Name", "Age", "Qualification", "Experience"])
def append_record(filename, record):
with open(filename, 'a', newline='') as file:
writer = csv.writer(file)
writer.writerow(record)
def display_all_records():
with open(filename, 'r') as file:
reader = csv.reader(file)
for row in reader:
print(', '.join(row))
def display_records_below_age(filename, age):
with open(filename, 'r') as file:
reader = csv.reader(file)
next(reader) # Skip the header row
for row in reader:
if int(row[1]) < age:
print(', '.join(row))
def increase_experience(filename):
with open(filename, 'r') as file:
reader = csv.reader(file)
header = next(reader)
data = []
for row in reader:
row[3] = str(int(row[3]) + 1
data.append(row)
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(header)
writer.writerows(data)
def delete_record(filename, name, age):
with open(filename, 'r') as file:
reader = csv.reader(file)
header = next(reader) # Read and skip the header row
data = []
for row in reader:
if row[0] != name or row[1] != age:
data.append(row)
with open(filename, 'w', newline='') as file:
writer = csv.writer(file)
writer.writerow(header)
writer.writerows(data)
# Initialize the CSV file with a header if it doesn't exist
csv_file = "data.csv"
write_csv_header(csv_file)
while True:
print("\nMenu:")
print("1. Append record(s)")
print("2. Display all records")
print("3. Display records with Age < 30")
print("4. Increase Experience by 1")
print("5. Delete a record by Name and Age")
print("6. Exit")
choice = input("Enter your choice: ")
if choice == '1':
name = input("Enter Name: ")
age = input("Enter Age: ")
qualification = input("Enter Qualification: ")
experience = input("Enter Experience: ")
append_record(csv_file, [name, age, qualification, experience])
print("Record(s) appended successfully.")
elif choice == '2':
print("All Records:")
display_all_records(csv_file)
elif choice == '3':
print("Records with Age < 30:")
display_records_below_age(csv_file, 30)
elif choice == '4':
increase_experience(csv_file)
print("Experience increased by 1 for all records.")
elif choice == '5':
name = input("Enter Name to delete: ")
age = input("Enter Age to delete: ")
delete_record(csv_file, name, age)
print("Record with Name "+ name +" and Age "+ str(age) deleted.")
elif choice == '6':
break
else:
print("Invalid choice. Please select a valid option.")
Q10. Write a program to implement a stack for these book- details (book no, book name).
that is now each item node of the stack contains two types of information – a book no and
its name. just implement Push, pop and display operations.
Ans:
def push(stack, book_no, book_name):
stack.append((book_no, book_name))
def pop(stack):
if not is_empty(stack):
popped_book = stack.pop()
print("Popped Book: Book No:", popped_book[0], ", Book Name:", popped_book[1])
else:
print("Stack is empty. Cannot pop.")
def is_empty(stack):
return len(stack) == 0
def display(stack):
if not is_empty(stack):
print("Stack contents:")
for book_no, book_name in reversed(stack):
print("Book No:", book_no, ", Book Name:", book_name)
else:
print("Stack is empty.")
book_stack = []
push(book_stack, "B001", "Book A")
push(book_stack, "B002", "Book B")
push(book_stack, "B003", "Book C")
display(book_stack)
pop(book_stack)
display(book_stack)
output
Q11. Each node of a STACK contains the following information:
a) Pincode of a city b) name of the city
Write a program to implement the following operations in the above stack:
a) PUSH () to push a node in to the stack
b) POP () to remove a node from the stack
c) PEEK () to get the topmost node from the stack
DISPLAY () to display all the nodes in the stack
Ans:
stack = []
def push(pincode, city_name):
stack.append((pincode, city_name))
def pop():
if not is_empty():
return stack.pop()
else:
print("Stack is empty. Cannot pop.")
return None
def peek():
if not is_empty():
return stack[-1]
else:
print("Stack is empty. Cannot peek.")
return None
def is_empty():
return len(stack) == 0
def display():
if not is_empty():
print("Stack contents:")
for pincode, city_name in reversed(stack):
print("Pincode: "+str(pincode)+ ", City Name: "+ city_name)
else:
print("Stack is empty.")
push("110018", "New Delhi")
push("11088", "JK")
push("110045", "UP")
display()
popped_city = pop()
if popped_city:
print("Popped City: Pincode: " + str(popped_city[0]) + ", City Name: " +
str(popped_city[1]))
peeked_city = peek()
if peeked_city:
print("Top City: Pincode: " + str(peeked_city[0]) + ", City Name: " + str(peeked_city[1]))
display()
Q12 SQL queries based on table SPORTS
Code
CREATE TABLE SPORTS (
StudentNo INT NOT NULL PRIMARY KEY,
Class VARCHAR(50) NOT NULL,
NAME VARCHAR(50) NOT NULL,
Cricket VARCHAR(50) NOT NULL,
Game1 VARCHAR(50) NOT NULL,
Grade1 ENUM('A', 'B', 'C') NOT NULL,
Swimming VARCHAR(50) NOT NULL,
Game2 VARCHAR(50) NOT NULL,
Grade2 ENUM('A', 'B', 'C') NOT NULL
);
INSERT INTO SPORTS (StudentNo, Class, NAME, Game1, Grade1, Game2, Grade2)
VALUES
(10, 'Sameer',7, 'Cricket', 'Game1', 'B', 'Swimming', 'Game2', 'A'),
(11, 'Sujit', 8,'Tennis', 'Game1', 'A', 'Skating', 'Game2', 'C'),
(12, 'Kamal', 7, 'Swimming', 'Game1', 'B', 'Football', 'Game2', 'B'),
(13, 'Venna', 7,'Tennis', 'Game1', 'C', 'Tennis', 'Game2', 'A'),
(14, 'Archana', 9, 'Basketball', 'Game1', 'A', 'Cricket', 'Game2', 'A'),
(15, 'Arpit', 10,'Cricket', 'Game1', 'A', 'Athletics', 'Game2', 'C');
(i)ans
(ii) ans
(iii) ans
Q13. SQL queries based on table TEACHER
Ans:
Answers to your questions:
(a) To show all information about the teacher of history department:
SELECT * FROM teacher WHERE Department = 'History';
(b) To list the names of female teachers who are in Hindi department:
SELECT Name FROM teacher WHERE Department = 'Hindi' AND Sex = 'F';
(c) To list names of all teachers with their date of joining in ascending order:
SELECT Name, DateOfJoin FROM teacher ORDER BY DateOfJoin ASC;
Q14. SQL queries based on table EMPLOYEE and JOB
(i): To display employee ids, names of employees, job ids with corresponding job titles.
SELECT EMPLOYEEID, NAME, JOB.JOBID, JOBTITLE FROM EMPLOYEE JOIN JOB ON EMPLOYEE.JOBID
= JOB.JOBID;
(ii): To display names of employees, sales and corresponding job titles who have achieved sales more
than 1300000.
SELECT NAME, SALES, JOBTITLE
FROM EMPLOYEE
JOIN JOB ON EMPLOYEE.JOBID = JOB.JOBID
WHERE SALES > 1300000;
(iii): To display names and corresponding job titles of those employees who have 'SINGH' (anywhere) in
their names.
SELECT NAME, JOBTITLE
FROM EMPLOYEE
WHERE NAME LIKE '%SINGH%';
(iv): Identify foreign key in the table EMPLOYEE.
The foreign key in the EMPLOYEE table is JOBID, which references the JOBID primary key in the
JOB table.
(v): Write SQL command to change the JOBID to 104 of the EMPLOYEE with ID as E4 in the table
'EMPLOYEE'.
UPDATE EMPLOYEE
SET JOBID = 104
WHERE EMPLOYEEID = 'E4';
Q15. SQL queries based on table EMPLOYEE and SALARY
Ans:
(i) To display the frequency of employees department wise.
SELECT Depid, COUNT(*) AS Frequency FROM employee GROUP BY Depid;
(ii) To list the names of those employees only whose name starts with ‘H’
SELECT NAME FROM employee WHERE NAME LIKE 'H%';
(iii) To add a new column in salary table. The column name is Total_Sal.
ALTER TABLE salary ADD Total_Sal INT;
(iv) To store the corresponding values in the Total_Sal column.
UPDATE salary s
JOIN (
SELECT e.Eid, (basic + da + hra + bonus) AS Total_Sal
FROM employee e
JOIN salary s ON e.Eid = s.eid
) AS subquery ON s.eid = subquery.Eid
SET s.Total_Sal = subquery.Total_Sal;
(v) Select max(Basic) from Salary where Bonus>40;
(vi) Select count(*) from Empoyee group by Sex;
(vii) Select Distinct Depid from Employee;
Q 16.SQL queries based on table PERSONAL and JOB
Ans:
(i)
Show empno,name and salary of those who have Sports as hobby.
(ii)
Show name of the eldest employee.
(iii)
Show number of emoployee are wise.
(iv)
Show youngest employees from each native place.
(v)
Show Sno, Name, Hoby and Salary in descending order of Salary.
(vi)
Show the hobbies of those whose name pronounces as ‘Abhay’
(vii)
Show the appointment data and native palace of those whose name start with
‘A’ or ends in ‘d’.
Q17. SQL queries based on table EMPLOYEES and EMPSALARY
Ans
(i)
To show firstname, lastname, address and city of all employees living in Paris:
SELECT firstname, lastname, address, city
FROM employees
WHERE city = 'Paris';
(ii)
to display the content of Employees table in descending order of Firstname:
SELECT *
FROM employees
ORDER BY firstname DESC;
(iii)
to display the firstname, lastname and total salary of all managers from the tables
Employes and EmpSalary, where total salary is calculated as Salary + Benefits:
SELECT employees.firstname, employees.lastname, EmpSalary.Salary +
EmpSalary.Benefits AS total_salary
FROM employees
INNER JOIN EmpSalary ON employees.empid = EmpSalary.Empid
WHERE EmpSalary.Designation = 'Manager';
(iv)
to display the maximum salary among managers and clerks from the table EmpSalary:
SELECT MAX(Salary) AS max_salary
FROM EmpSalary
WHERE Designation IN ('Manager', 'Clerk');
Q18. Write a function to read the content from the "quotes.txt" and transfer the content to
the file "duplicate.txt” but while transfer all the uppercase characters to lowercase
characters, lower case character to uppercase character and rest of the character as it is
def create():
f=open("quotes.txt","r")
f1=open("duplicate.txt","w")
str=f.read()
for i in str:
if i.isupper():
i=i.lower()
elif i.islower():
i=i.upper()
f1.write(i)
f.close()
f1.close()
create()
f1=open("duplicate.txt","r")
x=f1.read()
print(x)
f1.close()
output
Q19. Write a function AverageColumn () which accepts csv file as a parameter. It will print
sum and average of each row
import csv
data = [
["Name", "Math", "Science", "English"],
["Alice", 90, 85, 78],
["Bob", 88, 92, 95],
["Charlie", 76, 80, 88],
]
with open("marks.csv", "w", newline="") as csvfile:
csvwriter = csv.writer(csvfile)
csvwriter.writerows(data)
print("marks.csv created with sample data.")
def averagecolumn(csv_filename):
try:
with open(csv_filename, 'r') as f:
reader = csv.reader(f)
headers = next(reader) # Skip headers
column_sums = [0] * len(headers)
row_count = 0
for row in reader:
for i in range(1, len(headers)): # Start from 1 to skip the first column (Name)
column_sums[i] += float(row[i])
row_count += 1
print("Column Averages:")
for i in range(1, len(headers)): # Start from 1 to skip the first column (Name)
average = round(column_sums[i] / row_count, 2)
print(headers[i] + ":", average)
except Exception as e:
print("An error occurred:", e)
csv_filename = "marks.csv"
averagecolumn(csv_filename)
output
Q20. Write a function to read the contents from the file “India.txt”, and store the
frequency of each word in dictionary and display the dictionary in the screen
def word_count():
counts=dict()
f=open("India.txt","r")
count=0
str=f.read()
words=str.split()
for word in words:
if word in counts:
counts[word]+=1
else:
counts[word]=1
f.close()
return counts
print(word_count())
Q21. Write a menu driven program using function Push (), Pop () and Display () to
implement the stack. The program will store the employee details i.e., Employee number,
Employee name and Salary.
stack = []
def Push():
employee_number = input("Enter Employee Number: ")
employee_name = input("Enter Employee Name: ")
salary = input("Enter Salary: ")
employee = (employee_number, employee_name, salary)
stack.append(employee)
print("Employee details pushed onto the stack.")
def Pop():
if len(stack) == 0:
print("Stack is empty. Cannot pop.")
else:
popped_employee = stack.pop()
print("Popped Employee Details:")
print("Employee Number:", popped_employee[0])
print("Employee Name:", popped_employee[1])
print("Salary:", popped_employee[2])
def Display():
if len(stack) == 0:
print("Stack is empty.")
else:
print("Employee Details in the Stack:")
for employee in stack:
print("Employee Number:", employee[0])
print("Employee Name:", employee[1])
print("Salary:", employee[2])
print()
while True:
print("\nMenu:")
print("1. Push Employee Details")
print("2. Pop Employee Details")
print("3. Display Employee Details")
print("4. Exit")
choice = input("Enter your choice (1/2/3/4): ")
if choice == '1':
Push()
elif choice == '2':
Pop()
elif choice == '3':
Display()
elif choice == '4':
print("Exiting the program.")
break
else:
print("Invalid choice. Please select a valid option.")
Q22. Write a function update_record_rool(n) to read the student number as parameter
and update the record in student table.
Ans:
import mysql.connector
host="localhost"
user="root"
password=""
database="db_assign3"
def update_record_roll(student_number, new_data):
try:
connection = mysql.connector.connect(host,user, password, database)
cursor = connection.cursor()
update_query = "UPDATE student SET NAME= %s, address = %s WHERE
student_number = %s"
cursor.execute(update_query, (new_data[0], new_data[1], student_number))
connection.commit()
connection.close()
print("Record updated successfully!")
except Exception as e:
print("Error: " + str(e))
student_number = "12345"
new_data = ("Mohan Kumar", 'New Delhi'
update_record_roll(student_number, new_data)
Q23. Write a Python database connectivity script that will perform the following operations
on an SQL table of your choice:
1.Create a table.
2.Insert a row.
3.Display all records.
4.Search for a record based on the primary key value.
5.Update a record.
6.Deleate a record
Ans
import mysql.connector
def create_table(cursor):
table_query = """
CREATE TABLE IF NOT EXISTS students (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
age INT
)
"""
cursor.execute(table_query)
print("Table 'students' created successfully.")
def insert_row(cursor):
name = input("Enter student name: ")
age = int(input("Enter student age: "))
insert_query = "INSERT INTO students (name, age) VALUES (%s, %s)"
data = (name, age)
cursor.execute(insert_query, data)
print("Inserted row with name: " + str(name) + " and age: " + str(age))
def display_records(cursor):
select_query = "SELECT * FROM students"
cursor.execute(select_query)
records = cursor.fetchall()
for record in records:
print(record)
def search_record(cursor):
record_id = int(input("Enter student ID to search: "))
search_query = "SELECT * FROM students WHERE id = %s"
cursor.execute(search_query, (record_id,))
record = cursor.fetchone()
if record:
print(record)
else:
print("Record not found.")
def update_record(cursor):
record_id = int(input("Enter student ID to update: "))
new_name = input("Enter new name: ")
new_age = int(input("Enter new age: "))
update_query = "UPDATE students SET name = %s, age = %s WHERE id = %s"
data = (new_name, new_age, record_id)
cursor.execute(update_query, data)
print("Updated record with ID: " + str(record_id))
def delete_record(cursor):
record_id = int(input("Enter student ID to delete: "))
delete_query = "DELETE FROM students WHERE id = %s"
cursor.execute(delete_query, (record_id,))
print("Deleted record with ID: " + str(record_id))
try:
connection = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="db_assign3"
)
cursor = connection.cursor()
create_table(cursor)
while True:
print("\nMenu:")
print("1. Insert a student record")
print("2. Display all records")
print("3. Search for a student record")
print("4. Update a student record")
print("5. Delete a student record")
print("6. Exit")
choice = input("Enter your choice (1/2/3/4/5/6): ")
if choice == '1':
insert_row(cursor)
elif choice == '2':
display_records(cursor)
elif choice == '3':
search_record(cursor)
elif choice == '4':
update_record(cursor)
elif choice == '5':
delete_record(cursor)
elif choice == '6':
print("Exiting the program.")
break
else:
print("Invalid choice. Please select a valid option.")
connection.commit()
connection.close()
except Exception as e:
print("Error: " + str(e))
Q24. Write a Python database connectivity script that will perform the following operations
on an SQL table STUDENT:
1. Add a record
2.Display all records.
3.Display records in ascending order of names
4.Display records in descending order of percentage
5.Display the no of student in each stream
Ans
import mysql.connector
def create_table(cursor):
table_query = """
CREATE TABLE IF NOT EXISTS student (
id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(255),
age INT,
stream VARCHAR(255),
percentage FLOAT
)
"""
cursor.execute(table_query)
print("Table 'student' created successfully.")
def add_record(cursor):
name = input("Enter student name: ")
age = int(input("Enter student age: "))
stream = input("Enter student stream: ")
percentage = float(input("Enter student percentage: "))
insert_query = "INSERT INTO student (name, age, stream, percentage) VALUES (%s, %s, %s,
%s)"
data = (name, age, stream, percentage)
cursor.execute(insert_query, data)
print("Inserted record for " + name + " successfully.")
def display_all_records(cursor):
select_query = "SELECT * FROM student"
cursor.execute(select_query)
records = cursor.fetchall()
for record in records:
print(record)
def display_records_sorted_by_name(cursor):
select_query = "SELECT * FROM student ORDER BY name ASC"
cursor.execute(select_query)
records = cursor.fetchall()
for record in records:
print(record)
def display_records_sorted_by_percentage(cursor):
select_query = "SELECT * FROM student ORDER BY percentage DESC"
cursor.execute(select_query)
records = cursor.fetchall()
for record in records:
print(record)
def display_students_in_each_stream(cursor):
count_query = "SELECT stream, COUNT(*) FROM student GROUP BY stream"
cursor.execute(count_query)
counts = cursor.fetchall()
for stream, count in counts:
print("Stream: " + stream + ", Number of Students: " + str(count))
host="localhost",
user="root",
password="",
database="db_assign3"
connection = mysql.connector.connect(host, user, password, database )
cursor = connection.cursor()
create_table(cursor)
while True:
print("\nMenu:")
print("1. Add a student record")
print("2. Display all records")
print("3. Display records sorted by name")
print("4. Display records sorted by percentage")
print("5. Display the number of students in each stream")
print("6. Exit")
choice = input("Enter your choice (1/2/3/4/5/6): ")
if choice == '1':
add_record(cursor)
elif choice == '2':
display_all_records(cursor)
elif choice == '3':
display_records_sorted_by_name(cursor)
elif choice == '4':
display_records_sorted_by_percentage(cursor)
elif choice == '5':
display_students_in_each_stream(cursor)
elif choice == '6':
print("Exiting the program.")
break
else:
print("Invalid choice. Please select a valid option.")
connection.commit()
Q25. Write a Python database connectivity script that will perform the following operations
on an SQL table Books and Author
1.Add a record in table books.
2.Display all records of table books.
3.Display the books where the pin is between 1000 and 1500.
4.Display the names of authors whose names start with the letter 'M.'
5.Search for a specific book by book number
Ans:
import mysql.connector
def create_tables(cursor):
books_table_query = """
CREATE TABLE IF NOT EXISTS Books (
book_id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255),
author_id INT,
price FLOAT
)
"""
cursor.execute(books_table_query)
print("Table 'Books' created successfully.")
author_table_query = """
CREATE TABLE IF NOT EXISTS Author (
author_id INT AUTO_INCREMENT PRIMARY KEY,
author_name VARCHAR(255)
)
"""
cursor.execute(author_table_query)
print("Table 'Author' created successfully.")
def add_book(cursor):
title = input("Enter book title: ")
author_id = int(input("Enter author ID: "))
price = float(input("Enter book price: "))
insert_query = "INSERT INTO Books (title, author_id, price) VALUES (%s, %s, %s)"
data = (title, author_id, price)
cursor.execute(insert_query, data)
print("Inserted book." + title + " successfully.")
def display_all_books(cursor):
select_query = "SELECT * FROM Books"
cursor.execute(select_query)
records = cursor.fetchall()
for record in records:
print(record)
def display_books_in_price_range(cursor):
select_query = "SELECT * FROM Books WHERE price BETWEEN 10 AND 600"
cursor.execute(select_query)
records = cursor.fetchall()
for record in records:
print(record)
def display_authors_with_name_starting_with_m(cursor):
select_query = "SELECT author_name FROM Author WHERE author_name LIKE 'M%'"
cursor.execute(select_query)
authors = cursor.fetchall()
for author in authors:
print(author[0])
def search_book_by_number(cursor):
book_id = int(input("Enter book ID to search: "))
select_query = "SELECT * FROM Books WHERE book_id = %s"
cursor.execute(select_query, (book_id,))
record = cursor.fetchone()
if record:
print(record)
else:
print("Book not found.")
connection = mysql.connector.connect(
host="localhost",
user="root",
password="",
database="db_assign3"
)
cursor = connection.cursor()
create_tables(cursor)
while True:
print("\nMenu:")
print("1. Add a book record")
print("2. Display all books")
print("3. Display books in price range")
print("4. Display authors with names starting with 'M'")
print("5. Search for a specific book by book number")
print("6. Exit")
choice = input("Enter your choice (1/2/3/4/5/6): ")
if choice == '1':
add_book(cursor)
elif choice == '2':
display_all_books(cursor)
elif choice == '3':
display_books_in_price_range(cursor)
elif choice == '4':
display_authors_with_name_starting_with_m(cursor)
elif choice == '5':
search_book_by_number(cursor)
elif choice == '6':
print("Exiting the program.")
break
else:
print("Invalid choice. Please select a valid option.")
connection.commit()
Download