1. Write a function result to open a file [Link] in write mode.
Store names of 5
students along with the marks secured in english, maths and cs in a file.
def result():
# Open the file in write mode
with open("[Link]", "w") as file:
# Write the header
[Link]("Name\tEnglish\tMaths\tCS\n")
# Loop to get details of 5 students
for i in range(5):
name = input(f"Enter name of student {i+1}: ")
english = input(f"Enter marks in English for {name}: ")
maths = input(f"Enter marks in Maths for {name}: ")
cs = input(f"Enter marks in CS for {name}: ")
# Write to file
[Link](f"{name}\t{english}\t{maths}\t{cs}\n")
print("Data has been written to [Link] successfully.")
# Call the function
result()
2. Write a function Display to open the same file [Link] in read mode which
will return and display all the records available in [Link].
def Display():
try:
# Open the file in read mode
with open("[Link]", "r") as file:
# Read all lines
records = [Link]()
# Display each record
for record in records:
print([Link]()) # .strip() removes the newline character
return records # Return all records as a list
except FileNotFoundError:
print("[Link] file not found!")
return []
# Call the function
Display()
3. Write a function paragraph() in python to create a text file [Link] to write
a few lines into it. If you don’t want to write more lines, enter O to quit the
function.
def paragraph():
with open("[Link]", "w") as file:
print("Start writing your text. Enter 'O' to quit.")
while True:
line = input("Enter a line: ")
if [Link]() == "O": # Stop if user enters 'O' or 'o'
break
[Link](line + "\n") # Write line to file with newline
print("Your text has been saved in [Link].")
paragraph()
4. [Link] is a text file which contains a few names of the consumers. Write a
function display() in python to open the file in an appropriate mode to retrieve
the names. Count and display the names of all the consumers with the phone
number whose names start with the letter O.
def display():
try:
with open("[Link]", "r") as file:
count = 0 # Counter for names starting with 'O'
print("Consumers whose names start with 'O':")
for line in file:
line = [Link]() # Remove newline and spaces
if not line: # Skip empty lines
continue
parts = [Link]() # Split line into words
name = parts[0]
phone = " ".join(parts[1:]) # Rest is phone number
if [Link]().startswith("O"):
count += 1
print(f"{name} - {phone}")
print(f"\nTotal consumers with names starting with 'O': {count}")
except FileNotFoundError:
print("[Link] file not found!")
display()
5. Write a function display() in python which reads the integer numbers from a
binary file [Link]. Display only those numbers which are divisible by 3
and 5.
import pickle
def display():
try:
# Open the binary file in read mode
with open("[Link]", "rb") as file:
numbers = [Link](file) # Load the list of integers
print("Numbers divisible by 3 and 5:")
for num in numbers:
if num % 3 == 0 and num % 5 == 0:
print(num)
except FileNotFoundError:
print("[Link] file not found!")
except EOFError:
print("[Link] is empty!")
except Exception as e:
print("An error occurred:", e)
display()
6. Write a function vowel() which reads binary file [Link] containing name and
registration number. Display only the names along with the registration
number. From the file whose first letter is a vowel.
import pickle
def vowel():
vowels = "AEIOU" # Vowels to check (uppercase)
try:
# Open the binary file in read mode
with open("[Link]", "rb") as file:
data = [Link](file) # Load list of tuples [(name, reg_no), ...]
print("Names starting with a vowel and their registration numbers:")
for entry in data:
name, reg_no = entry
if name[0].upper() in vowels:
print(f"{name} - {reg_no}")
except FileNotFoundError:
print("[Link] file not found!")
except EOFError:
print("[Link] is empty!")
except Exception as e:
print("An error occurred:", e)
vowel()
7. A file [Link] has already been created with the records containing index
number, name, marks and grade as sublists of a list. Later on the user realised
that he made a wrong entry of the grades in all records. Define a function
update to open the file in rb+ mode to read and update. The grades in all the
records as mentioned below:
Marks - 90 and above - Grade A
Marks - 80<=x<90 - Grade B
Marks - else - Grade C
import pickle
def update():
try:
# Open the file in rb+ mode (read & write binary)
with open("[Link]", "rb+") as file:
data = [Link](file) # Read the list of records
# Update grades based on marks
for record in data:
marks = record[2] # Marks are at index 2
if marks >= 90:
record[3] = "A"
elif 80 <= marks < 90:
record[3] = "B"
else:
record[3] = "C
# Go back to the start of the file to overwrite it
[Link](0)
[Link](data, file) # Write updated data back
[Link]() # Remove any leftover old data
print("Grades have been updated successfully.")
except FileNotFoundError:
print("[Link] file not found!")
except EOFError:
print("[Link] is empty!")
except Exception as e:
print("An error occurred:", e)
update()
8. Write a python code to create a file [Link] to keep the records of package
trips to different places with their tariffs.
import csv
def create_trip_file():
# Open [Link] in write mode
with open("[Link]", "w", newline="") as file:
writer = [Link](file)
# Write the header
[Link](["Place", "Package", "Tariff"])
# Example records of trips
trips = [
["Goa", "Beach Fun", 15000],
["Manali", "Himalayan Adventure", 20000],
["Kerala", "Backwater Cruise", 18000],
["Jaipur", "Heritage Tour", 12000],
["Darjeeling", "Tea Garden Trip", 17000]
]
# Write the records to the CSV file
[Link](trips)
print("[Link] has been created successfully.")
# Call the function
create_trip_file()
9. Write a function trip() to read all the records of the file [Link] and display
details of different places along with tariffs.
import csv
def trip():
try:
# Open [Link] in read mode
with open("[Link]", "r") as file:
reader = [Link](file)
print("Trips and Tariffs:\n")
# Read the header
header = next(reader)
print(f"{header[0]:<15} {header[1]:<25} {header[2]:<10}")
print("-" * 50)
# Read and display each row
for row in reader:
place, package, tariff = row
print(f"{place:<15} {package:<25} {tariff:<10}")
except FileNotFoundError:
print("[Link] file not found!")
except Exception as e:
print("An error occurred:", e)
# Call the function
trip()
10.Create a table Employee with the following fields:
EmpCode, Name, Dept, Salary, Ph. No.
(a) Write the query to insert records to the table employee.
(b)Write the query to add a new column ‘Gender’ with a default value to the table
Employee.
(c) Modify the names of the employees with Emp_Code E3 to a value according to
our choice.
(d)Increase the salary of all the employees who get less than 4000 Rs. by 2000 Rs.
(e) Write the query to arrange the data for table employees in ascending order of
name.
(f) Write the query to delete the record for the employee whose Emp_code is 2.
(g)Write a query to change the data type of Dept. from char to varchar.
(h)Write a query to display the number of records in the table employee.
(i) Write the query to display the content of the table.
(j) Write a query to display names of employees with exactly 5 characters.
(k) Write a query to display the number of values in each column.
(l) Write a query to Delete column ‘Gender’.
(m)Write a query to display the records of those employee whose Dept. is
mechanical.
CREATE TABLE Employee (
EmpCode VARCHAR(5) PRIMARY KEY,
Name VARCHAR(50),
Dept CHAR(20),
Salary INT,
PhNo VARCHAR(15));
INSERT INTO Employee (EmpCode, Name, Dept, Salary, PhNo) VALUES
('E1', 'Alice', 'Mechanical', 3500, '9876543210'),
('E2', 'Bob', 'Electrical', 4500, '9876543211'),
('E3', 'Charlie', 'Civil', 3000, '9876543212'),
('E4', 'David', 'Mechanical', 5000, '9876543213');
ALTER TABLE Employee
ADD COLUMN Gender CHAR(1) DEFAULT 'M';
UPDATE Employee
SET Name = 'Chris'
WHERE EmpCode = 'E3';
UPDATE Employee
SET Salary = Salary + 2000
WHERE Salary < 4000;
SELECT * FROM Employee
ORDER BY Name ASC;
DELETE FROM Employee
WHERE EmpCode = 'E2';
ALTER TABLE Employee
MODIFY Dept VARCHAR(50);
SELECT COUNT(*) AS TotalEmployees FROM Employee;
SELECT * FROM Employee;
SELECT Name FROM Employee
WHERE LENGTH(Name) = 5;
SELECT
COUNT(EmpCode) AS EmpCodeCount,
COUNT(Name) AS NameCount,
COUNT(Dept) AS DeptCount,
COUNT(Salary) AS SalaryCount,
COUNT(PhNo) AS PhNoCount,
COUNT(Gender) AS GenderCount
FROM Employee;
ALTER TABLE Employee
DROP COLUMN Gender;
SELECT * FROM Employee
WHERE Dept = 'Mechanical';