Question 1:
A binary file named “[Link]” has some records of the structure [EmpNo, EName, Post,
Salary].
1. Write a user-defined function named NewEmp() to input the details of a new
employee from the user and store it in [Link].
2. Write a function to display number of employees having Salary more than 20000.
3. Write a user-defined function named SumSalary(Post) that will accept an argument
the post of employees & read the contents of [Link] and calculate the SUM of
salary of all employees of that Post.
4. Create a menu driven code to call above functions.
Question 2:
Imagine you work for a retail company that stores its daily sales data in a CSV file named
"sales_data.csv".
Develop a Python script using the csv module to:
1. Add records in the file.
2. Read this file and generate a daily sales report.
3. Create a report, the report should include total sales revenue, the number of items
sold, and a breakdown of sales by product category.
4. Write a menu driven code for above
Question 3:
Write a Python program that uses a CSV file named "[Link]".The CSV file contains
columns for "Product", "Quantity", and "Price".
1. Write a function to asks the user for the values and write the data in a CSV file named
"[Link]"
2. Write a function to reads data from a CSV file named "[Link]"using the
[Link]() class.
3. Your program should calculate the total value of each product in inventory (quantity *
price)
and print a summary report showing each product's name and total value.
Code for Question 1:
import pickle
FILENAME = "[Link]"
# 1. Function to add new employee
def NewEmp():
with open(FILENAME, "ab") as file:
ch = 'y'
while [Link]() == 'y':
empno = int(input("Enter Employee Number: "))
name = input("Enter Employee Name: ")
post = input("Enter Post: ")
salary = int(input("Enter Salary: "))
record = [empno, name, post, salary]
[Link](record, file)
print("Employee record added successfully!\n")
ch = input("Add more records? (y/n): ")
# 2. Function to display the detials of the asked employee
def DisplayEmp():
empcode = int(input("Enter Employee Code to search: "))
found = False
try:
with open(FILENAME, "rb") as file:
while True:
record = [Link](file)
if record[0] == empcode:
print("\nEmployee Details")
print("Employee Number :", record[0])
print("Name :", record[1])
print("Post :", record[2])
print("Salary :", record[3])
found = True
break
except EOFError:
pass
if not found:
print("Employee record not found!")
# 3. Function to calculate sum of salary by Post
def SumSalary(Post):
total = 0
try:
with open(FILENAME, "rb") as file:
while True:
record = [Link](file)
if record[2].lower() == [Link]():
total += record[3]
except EOFError:
pass
print("Total salary of", Post, ":", total)
# 4. Menu-driven program
while True:
print("\nMENU")
print("1. Add New Employee")
print("2. Display the detials of the employee")
print("3. Sum of Salary by Post")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == '1':
NewEmp()
elif choice == '2':
DisplayEmp()
elif choice == '3':
post = input("Enter Post: ")
SumSalary(post)
elif choice == '4':
print("Exiting program.")
break
else:
print("Invalid choice! Try again.")
Code for Question 2:
import csv
FILENAME = "sales_data.csv"
# Create file with header if it does not exist
def create_file():
try:
with open(FILENAME, "r"):
pass
except FileNotFoundError:
with open(FILENAME, "w", newline="") as file:
writer = [Link](file)
[Link](["Date", "Product", "Category", "Quantity", "Price"])
# Add sales record
def add_record():
ch = 'y'
with open(FILENAME, "a", newline="") as file:
writer = [Link](file)
while [Link]() == 'y':
date = input("Enter Date (DD-MM-YYYY): ")
product = input("Enter Product Name: ")
category = input("Enter Product Category: ")
quantity = int(input("Enter Quantity Sold: "))
price = float(input("Enter Price per Item: "))
[Link]([date, product, category, quantity, price])
print("Record added successfully!\n")
ch = input("Add more records? (y/n): ")
# Generate daily sales report
def sales_report():
total_revenue = 0
total_items = 0
category_sales = {}
with open(FILENAME, "r", newline="") as file:
reader = [Link](file)
for row in reader:
quantity = int(row["Quantity"])
price = float(row["Price"])
category = row["Category"]
revenue = quantity * price
total_revenue += revenue
total_items += quantity
if category in category_sales:
category_sales[category] += revenue
else:
category_sales[category] = revenue
print("\nDAILY SALES REPORT")
print("-" * 40)
print("Total Revenue : ₹", total_revenue)
print("Total Items Sold :", total_items)
print("\nSales by Category:")
for cat, value in category_sales.items():
print(f"{cat} : ₹{value}")
print("-" * 40)
# Update record by product name
def update_record():
records = []
found = False
pname = input("Enter Product Name to update: ")
with open(FILENAME, "r", newline="") as file:
reader = [Link](file)
for row in reader:
if row["Product"].lower() == [Link]():
print("Enter new details:")
row["Quantity"] = input("New Quantity: ")
row["Price"] = input("New Price: ")
found = True
[Link](row)
if found:
with open(FILENAME, "w", newline="") as file:
writer = [Link](file, fieldnames=records[0].keys())
[Link]()
[Link](records)
print("Record updated successfully!")
else:
print("Product not found!")
# Main Program
create_file()
while True:
print("\nMENU")
print("1. Add Sales Record")
print("2. Generate Sales Report")
print("3. Update Sales Record")
print("4. Exit")
choice = input("Enter your choice (1-4): ")
if choice == "1":
add_record()
elif choice == "2":
sales_report()
elif choice == "3":
update_record()
elif choice == "4":
print("Exiting program. Thank you!")
break
else:
print("Invalid choice! Try again.")
Code for Question 3:
import csv
FILENAME = "[Link]"
def add_product():
ch = 'y'
with open(FILENAME, "a", newline="") as file:
writer = [Link](file)
while ch == 'y' or ch == 'Y':
product = input("Enter Product Name: ")
quantity = int(input("Enter Quantity: "))
price = float(input("Enter Price: "))
[Link]([product, quantity, price])
print("Product added successfully!\n")
ch = input("Do you want to add more (y/n): ")
def display_inventory():
try:
with open(FILENAME, "r", newline="") as file:
reader = [Link](file)
print("\nInventory Summary Report")
print("-" * 40)
for row in reader:
product = row["Product"]
quantity = int(row["Quantity"])
price = float(row["Price"])
total_value = quantity * price
print(f"Product Name : {product}")
print(f"Total Value : ₹{total_value}")
print("-" * 40)
except FileNotFoundError:
print("File not found! Please add products first.\n")
def create_file_if_not_exists():
try:
with open(FILENAME, "r"):
pass
except FileNotFoundError:
with open(FILENAME, "w", newline="") as file:
writer = [Link](file)
[Link](["Product", "Quantity", "Price"])
# Main Program
create_file_if_not_exists()
while True:
print("MENU")
print("1. Add Product to Inventory")
print("2. Display Inventory Report")
print("3. Exit")
choice = input("Enter your choice (1-3): ")
if choice == "1":
add_product()
elif choice == "2":
display_inventory()
elif choice == "3":
print("Exiting program. Thank you!")
break
else:
print("Invalid choice! Please try again.\n")